views:

45

answers:

4

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

A: 

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();
}
Moin Zaman
that was one of the problems the LevelListID are not immediate parents of both cartID and CheckBoxID I was trying to use .parentsUntil() but didn't get it to work
Oudin
A: 

This should work:

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

Seems like the condition you need is:

if (levelListID==$('#'+checkBoxID).closest('li').attr('id')) {
 ...
}
bazmegakapa
Got this one to work only thing the comer (,) before attr needs to be changed to a full stop(.)
Oudin
A: 

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.

Nick Craver
tried this one the problem with it is once the check-box is clicked you can use any button to activate it thanks for though
Oudin