M Kenyon II M Kenyon II - 7 months ago 14
Javascript Question

How do I get a <div> on a nearby node in the DOM?

I'm trying to write some JavaScript that could be used throughout my app, and allow a checkbox to show/hide a nearby element.

If I have these elements:

<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control"
data-val="true" id="IsActive"
name="IsActive"
onclick="CheckboxOptionsToggle(this);"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>


And this script:

CheckboxOptionsToggle = function (thisCheckbox) {
debugger;
var optionElement = $('.options');
if (thisCheckbox.checked) {
$(thisCheckbox).closest(optionElement).show();
} else {
$(thisCheckbox).closest(optionElement).hide();
}
}


But this isn't working. I would like the checkbox with the
onclick="CheckboxOptionsToggle(this);"
to trigger the
options
element in the same
optionable
div to either show or hide.

What am I doing wrong in my JavaScript/jQuery?

UPDATE: This is my final solution:

$('.optionToggle').on('change', function () {
$(this).closest('.optionable').find('.options').toggle(this.checked);
});
$(document).ready(function () {
var toggleElements = document.body.getElementsByClassName('optionToggle');
for (var i = 0; i < toggleElements.length; i++) {
var thisCheck = $(toggleElements[i]);
thisCheck.closest('.optionable').find('.options').toggle(thisCheck.prop('checked'));
}
});

<div class="optionable" style="display: block;">
<div class="row">
<div class="col-md-2">
<input checked="checked" class="form-control optionToggle"
data-val="true" id="IsActive"
name="IsActive"
type="checkbox" value="true">
</div>
<div class="col-md-8">
Chapter
</div>
</div>
<div class="row options">
<div class="col-md-12">
Some data here...
</div>
</div>
</div>

Answer

Be more generic, and stop using inline event handlers

$('[type="checkbox"]').on('change', function() { // or use class to not attach to all

    $(this).closest('.optionable').find('.options').toggle(this.checked);

});

FIDDLE