【问题标题】:if to check whenever a radio is checked or not是否检查收音机是否检查
【发布时间】:2015-08-26 15:19:28
【问题描述】:

我用这样的 php 在表单中输出一堆输入复选框和单选按钮

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 是一个复选框时,它可以正常工作。我该怎么做才能解决这个问题?

【问题讨论】:

  • 您可以在.product 上使用.each(),并在每次更改事件期间找出total

标签: php jquery checkbox radio checked


【解决方案1】:
$(document).ready(function() {    
 $(".product").change(function(){   
    var price = $(".product").attr('data-price');    
    if ($(".product").attr("checked")){
       total = total + price;
    }
    else
    {
       total = total - price;
    }
 });

});

【讨论】:

  • 这总是返回 false
【解决方案2】:

显然达不到。因为radio 按钮不会像checkbox 那样有unchecked 事件。所以你需要为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;
    }
});

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多