Lukas Baliƫnas Lukas Baliƫnas - 3 months ago 7
HTML Question

JQuery Disable inputs, when option is selected

I have 2 options:

#home-none
and
#home-select
, when #home-none is selected i want all my inputs with class
.home
to be disabled.

HTML:

Options

<select class="form-control">
<option id="home-none">-</option>
<option id="home-select">Team</option>
</select>


Inputs

<div class="form-group">
<input class="form-control home" name="h-p1-fn" placeholder="First name" type="text"/>
</div>
<div class="form-group">
<input class="form-control home" name="h-p1-ln" placeholder="Last name" type="text"/>
</div>


JS:

<script type="text/javascript">
$(document).ready(function(){
$("#home-select").click(function(){
$(".home").prop('disabled',true);
});
$("#home-none").click(function(){
$(".home").prop('disabled',true);
});
});
</script>


The console doesn't show errors, but it doesn't work.

Answer

You're hooking to the wrong event. Use the change event of the select instead. From there you can read the value attribute of the option elements to set the relevant input elements as disabled. Try this:

$(document).ready(function(){
  $("select.form-control").change(function(){
    $(".home").prop('disabled', $(this).val() == 'home-none');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
    <option value="home-none">-</option>
    <option value="home-select">Team</option>
</select>

<div class="form-group">
    <input class="form-control home" name="h-p1-fn" placeholder="First name" type="text"/>
</div>
<div class="form-group">
    <input class="form-control home" name="h-p1-ln" placeholder="Last name" type="text"/>
</div>

Comments