Dark Cyber Dark Cyber - 2 months ago 16
jQuery Question

Bootstrap How to enable/disable input on option selected?

I want to make form which say if Item is stockable then stock input will be enable, else stock input will be disabled.

I am looking for bootstrap shortcut if any.

Here is my code so far.

<div class="form-group">
<label>Is item stockable?</label>
<select name="stockable" class="form-control">
<option value="">Choose</option>
<option value="0">No, Item is not stockable</option>
<option value="1">Yes, Item is stockable</option>
</select>
</div>

<div class="form-group">
<label>Stok</label>
<input class="form-control" placeholder="" name="stock" type="text" disabled>
</div>


If there is no bootstrap shortcut, I hope there is simple and easy way to do with jQuery.

Answer

Use a change event,toggle the disabled property based on the value of the select using a if

$('select[name="stockable"]').change(function(){
 if($(this).val() != 0) {
 $('input[name="stock"]').prop('disabled',false);
 } else {$('input[name="stock"]').prop('disabled',true);}
});

or:

$(document).ready(function(){
 $('select[name="stockable"]').change(function(){
   $('input[name="stock"]').prop('disabled',this.value != 0 ?false:true);
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label>Is item stockable?</label>
  <select name="stockable" class="form-control">
    <option value="">Choose</option>
    <option value="0">No, Item is not stockable</option>
    <option value="1">Yes, Item is stockable</option>
  </select>
</div>

<div class="form-group">
  <label>Stok</label>
  <input class="form-control" placeholder="" name="stock" type="text" disabled>
</div>

note: better go with some radio buttons here, your select has only 2 values