Question

Hi I am working on this piece of code for a shopping cart

$('.addtoCart').click(function() {

    //get button id      
    var cartID = $(this).attr("id"); 

    //get check box id   
    var checkBoxID = $('input.cartLevelChecked:checked').attr("id");

    //get parent id
    var levelListID = $(this).closest('li').attr("id");

    if(('#'+cartID && '#'+checkBoxID).parent('#'+levelListID)){
        $(".selectPlan").show();
    }

    //alert(/*cartID + checkBoxID +*/ levelListID);
});

Basically I'm checking to see if the check-box the user checked and button they clicked on belongs to the same parent then show a div

any help would be greatly appreciated. thanks

Was it helpful?

Solution

You need to compare levelListID, which you correctly queried, to the id of the checkbox's closest li parent, which you should query the same way:

if (levelListID === $('#' + checkBoxID).closest('li').attr('id')) {
    ...
}

OTHER TIPS

This should work:

//compares the parent() HTMLElement (not the jQuery object)
if ( $(this).parent().get(0) == $('input.cartLevelChecked:checked').parent().get(0) ) {
     $(".selectPlan").show();
}

you were almost there, this should work if the parent is the immediate parent of both cartID and checkBoxID:

if($('#'+cartID).parent().attr(id) == levelListID && $('#'+checkboxID).parent().attr(id) == levelListID ) {
    $(".selectPlan").show();
}

You can just go up to the <li> parent and see if the checked element exists in there, like this:

$('.addtoCart').click(function() {
  if($(this).closest('li').find('input.cartLevelChecked:checked').length) {
    //yes we're in the same parent
  }
});

This uses .closest() to go the parent <li> then looks inside for the checkbox using .find(). Then we're just checking that the .length isn't 0 (true) which means it found one checked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top