是否检查无线电是否被检查

时间:2015-06-11 05:19:27

标签: php jquery checkbox radio checked

我使用像这样的

输出表格中的一堆输入复选框和单选按钮
if($product['type']==1)
{
    $selector = "<input type='checkbox' class='product' data-price='".$product['price']."' name='prod_".$product['pid']."' id='prod_".$product['pid']."' value='".$product['pid']."'>";
}
elseif($product['type']==2)
{
    $selector = "<input type='radio' required class='product' data-price='".$product['price']."' name='cat_".$product['id']."' id='cat_".$product['id']."' value='".$product['pid']."'>";   
}

正如您所看到的,这些输入框包含data-price元素和product

然后我使用jquery来监听产品类的元素何时发生变化

$(".product").change(function(){
    var product = $(this); 
    var price = product.data('price');
    if(product.is(':checked')) {    
       total = total + price;
    } else {
       total = total - price;
    }
});

我的问题是,当product var是一个单选按钮时,上面的内容永远不会到达else子句。当product var是一个复选框时,它可以正常工作。我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

$(document).ready(function() {    
 $(".product").change(function(){   
    var price = $(".product").attr('data-price');    
    if ($(".product").attr("checked")){
       total = total + price;
    }
    else
    {
       total = total - price;
    }
 });

});

答案 1 :(得分:0)

显然无法达到。因为与radio不同,unchecked按钮不会有checkbox个事件。因此,您需要将radio按钮的事件写入uncheck,然后编写点击事件。因此,在添加和JS事件更改时,请在下方更改单选按钮,如下所示:

else if($product['type']==2)
{
    $selector = "<input type='radio' name="foo" required class='product' data-price='".$product['price']."' name='cat_".$product['id']."' id='cat_".$product['id']."' value='".$product['pid']."'>"; 
   makeRadiosDeselectableByName('foo');// Call after appending  
}

现在添加一个自定义JS

DEMO 使radio可选择和取消选择

var makeRadiosDeselectableByName = function(name){
    $('input[name=' + name + ']').click(function() {
        if($(this).data('previousValue') == 'true'){
            $(this).attr('checked', false)
        } else {
            $('input[name=' + name + ']').data('previousValue', false);
        }

        $(this).data('previousValue', $(this).attr('checked'));
    });
};

现在你的功能应该正常工作

$(".product").click(function(){
    var product = $(this); 
    var price = product.data('price');
    if(product.is(':checked')) {    
       total = total + price;
    } else {
       total = total - price;
    }
});