仅在选中单选按钮时才进行验证

时间:2012-08-29 18:30:09

标签: jquery magento magento-1.4

我正在尝试修改PO Box验证脚本,以便仅在选中“发送到此地址”时对其进行验证。该表单显然使用really easy form validation。表格部分是:

        <input type="radio" name="billing[use_for_shipping]" id="billing:use_for_shipping_yes" value="1" <?php if ($this->isUseBillingAddressForShipping()) {?> checked="checked"<?php }?> title="<?php echo  $this->__('Ship to this address') ?>" onclick="$('shipping:same_as_billing').checked = true;" class="radio" /><label for="billing:use_for_shipping_yes"><?php echo  $this->__('Ship to this address') ?></label></li>
    <li class="control">
        <input type="radio" name="billing[use_for_shipping]" id="billing:use_for_shipping_no" value="0" <?php if (!$this->isUseBillingAddressForShipping()) {?> checked="checked"<?php }?> title="<?php echo $this->__('Ship to different address') ?>" onclick="$('shipping:same_as_billing').checked = false;" class="radio" /><label for="billing:use_for_shipping_no"><?php echo $this->__('Ship to different address') ?></label>

到目前为止,脚本是

Validation.add('validate-pobox', 'One or more items purchased cannot be shipped to a PO Box', function (v){
    var pattern =  /\b([P|p](OST|ost)?\.?\s?[O|o|0](ffice|FFICE)?\.?\s)?([B|b][O|o|0][X|x])\s(\d+)/;
    if( document.getElementById("billing:use_for_shipping_yes").checked) // this isn't working
        if (!pattern.test(v)) return true; else return false;
});

我不熟悉jQuery(我正在慢慢学习!),但无论我尝试什么,无论选择哪个按钮,脚本仍会验证地址字段。我也试过了:

if( $("billing:use_for_shipping_yes").checked)
if( $("billing:use_for_shipping_yes").is("checked"))

1 个答案:

答案 0 :(得分:0)

尝试添加冒号进行检查。而且您忘记了复选框http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html

的ID的#
if( $("#billing:use_for_shipping_yes").is(":checked"))

根据我可以看到的代码看起来应该是这样的

Validation.add('validate-pobox', 'One or more items purchased cannot be shipped to a PO Box', function (v){
    var pattern =  /\b([P|p](OST|ost)?\.?\s?[O|o|0](ffice|FFICE)?\.?\s)?([B|b][O|o|0][X|x])\s(\d+)/;
    if( $("#billing:use_for_shipping_yes").is(":checked")) {
        if (!pattern.test(v)) {
            return true;
        } else { 
            return false;
        }
    }
});