Search code examples
jquerycheckboxradio-buttonshopping-cart

Basic shopping cart - Why is my Radio button state referenced incorrectly?


I have a very simple "shopping cart" built in jQuery. (all on one page). You add the items by checking a checkbox and remove them by unchecking the checkbox. However the state of the checkbox is not being referenced correctly and therefore I cannot enter the "add to cart" portion of the if else statement below:

$('#coreSetM').click(function()
{ 
    // Get the value of radio button
    var theMValue = $(this).attr("value");
    var theMPackage = $(this).attr("id");
    var theChecked = $(this).is(':checked');

    console.log("Value:"+theMValue+"\nPackage:"+theMPackage+"\nCheck Value:"+theChecked);

    if(theChecked==="false")
    {
        alert("False: "+theChecked);
        //do some add to cart stuff here with innerHTML
    }
    else
    {
        alert("True: "+theChecked)
        //do some remove from cart stuff here with innerHTML
    }
});

Despite the console logging the following:-

Value:118
Package:coreSetM
Check Value:false 

Value:118
Package:coreSetM
Check Value:true

It never enters the first part of the loop... I cannot figure out why since the value of theChecked is "false". (as determined in the console output.) Why is this?


Solution

  • Missing a closing )

    EDIT: You are comparing boolean to string by using theChecked === 'false'. Switch this to theChecked === false and you should be fine

    Updated fiddle: https://jsfiddle.net/t6rfwbaf/