Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show hidden fields when checkbox is checked?

Hi I have multiple checkboxes of similar kind. I am applying javascript on the checkbox to show hidden fields. I have created a js code which works for a single checkbox, I want to apply a code that will work for all checkboxes.

<div class="row">
  <div class="col-md-12">
      <div class="form-group">
          <div class="col-md-2">
             <label>Practical Course:</label>&nbsp;&nbsp;
             <input id="checkbox" type="checkbox">
          </div>

          <div class="col-md-4" id="box" style="display: none;">
               <input type="number" name="practical1" class="form-control">
          </div>
       </div>
    </div>
 </div>

 <div class="row">
  <div class="col-md-12">
      <div class="form-group">
          <div class="col-md-2">
             <label>Practical Course:</label>&nbsp;&nbsp;
             <input id="checkbox" type="checkbox">
          </div>

          <div class="col-md-4" id="box" style="display: none;">
               <input type="number" name="practical2" class="form-control">
          </div>
       </div>
    </div>
 </div>

JS Code :-

var checkbox = document.getElementById('checkbox');
var box = document.getElementById('box');
checkbox.onclick = function() {
    console.log(this);
    if (this.checked) {
        box.style['display'] = 'block';
    } else {
        box.style['display'] = 'none';
    }
};    

Now the thing is i can make individual javascript for all checkboxes but that will contain numerous js code, I want that a single javascript function can unhide the elements from every checkbox when clicked. A single js code should work for all checkboxes. Kindly please provide a way of doing it with plain javascript or jquery.

like image 777
Kartikey Vishwakarma Avatar asked May 09 '26 12:05

Kartikey Vishwakarma


1 Answers

Try this on your check box's onchange event call function onchange="showHiddenField(this)"

and function is like

function showHiddenField(currentObject) {
    var inputDiv = $(currentObject).parent().next();
    if ($(currentObject).is(":checked")) {
        $(inputDiv).show().focus();
    }
    else {
        $(inputDiv).hide();
    }
}
like image 139
Jitendra Joshi Avatar answered May 12 '26 02:05

Jitendra Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!