if to check whenever a radio is checked or not

350 views Asked by At

I output a bunch of input checkboxes and radio buttons in a form using php like this

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']."'>";   
}

As you can see these input boxes hold a data-price element and a class of product

Im then using jquery to listen for when elements with the product class change like this

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

My problem is that the above never reaches the else clause when the product var is a radio button. It works without problems when the product var is a checkbox. What can i do to solve this?

2

There are 2 answers

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

});
0
Guruprasad J Rao On

Obviously it will not reach. because radio button will not have unchecked event unlike checkbox. So you need to write a event for radio button to uncheck it and write a click event instead. So make below changes to your radio button while adding and some JS event change as below:

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  
}

Now Add one custom JS

DEMO to make radio selectable and deselectable

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'));
    });
};

Now your function should work

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