javascript - JQuery: how to find element that lies after current element -


suppose, have 2 checkboxes , 2 divs follow checkboxes:

enter image description here

<div class="wrapper">     <input type="checkbox" name="checkbox1" checked="" /> </div> <div class="border"></div>  <div class="wrapper">     <input type="checkbox" name="checkbox2" checked="" /> </div> <div class="border"></div> 

my goal toggle color of appropriate "border" div, lying below checkbox. problem is, don't know how appropriate div. tried this, doesn't work:

$('input[type="checkbox"]').change(     function  ()     {         var div = $(this).find('div');//<-- ?          if ($(this).checked)         {             div.css("border", "solid 2px blue");         }         else         {             div.css("border", "solid 2px black");         }     }); 

jsfiddle

the problem .find() method select descendant elements.

since input element self-closed , doesn't contain descendant elements, nothing selected $(this).find('div').

you select parent div element, , following element:

$(this).parent().next(); 

the above select immediate parent element. may safer using .closest() method in order select ancestor .wrapper element (just in case nesting varies):

$(this).closest('.wrapper').next(); 

in addition, jquery objects don't have checked property, should retrieve checked property of dom element, therefore $(this).checked should this.checked or use .prop() method retrieve checked property dom element in jquery object using: $(this).prop('checked').

updated example

$('input[type="checkbox"]').on('change', function() {   var div = $(this).closest('.wrapper').next();    if (this.checked) {     div.css("border", "solid 2px blue");   } else {     div.css("border", "solid 2px black");   } }); 

as side note, i'd suggest toggling class on corresponding element instead:

updated example

.border.blue-border {   border-color: blue; } 
$('input[type="checkbox"]').on('change', function() {   $(this).closest('.wrapper').next().toggleclass('blue-border') }); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -