문제

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

도움이 되었습니까?

해결책

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')) {
    ...
}

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top