Lunasil
Lunasil

Reputation: 63

Some inputs disabled when checked option

Hello i would like to add function to my form when i select one option then some inputs of my form are disabled i tried to do this in jquery but something is not working.Could u help me wit this?

There is a example form:

<div class="col-4">
   <label>Enabled </label>
   <select name="stato" id="stato" class="form-control">
      <option value="Text1">Text1</option>
      <option value="Text2">Text2</option>
      <option value="Text3">Text3</option>
      <option value="Text4">Text4</option>
   </select>
</div>
 
<div class="col-4" >
   <label>Disabled when choose option in select</label>
   <input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
</div>

and function in jquery

$(function() {
  $('#data_consegna').prop('disabled', true);
  $('#stato option').each(function() {
    if ($(this).is('selected')) {
      $('#data_consegna').prop('enabled', true);
    } else {
      $('#data_consegna').prop('enabled', false);
    }
  });
});

Upvotes: 2

Views: 117

Answers (1)

Fakhrul Hasan
Fakhrul Hasan

Reputation: 162

enter code here

$(function() {
        //Triggering change event handler on element #stato
        $('#stato').change(function() {
            var value = $(this).val(); //Getting selected value from #stato
            if (value == "") {
                $('.common_disable').prop('disabled', false); //If value is empty then disable another field
            } else {
                $('.common_disable').prop('disabled', true); //Else enable another field
            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
   <label>Enabled </label>
   <select name="stato" id="stato" class="form-control">
        <option value="">Select One</option>
        <option value="Text1">Text1</option>
        <option value="Text2">Text2</option>
        <option value="Text3">Text3</option>
        <option value="Text4">Text4</option>
   </select>
</div>
 
<div class="col-4" >
   <label>Disabled when choose option in select</label><br>
   <input id="data_consegna" type="text" class="form-control common_disable" name="data_consegna" placeholder="Data Consegna" /><br>
   <input id="data_consegna2" type="text" class="form-control common_disable" name="data_consegna2" placeholder="Data Consegna2" /><br>
   <input id="data_consegna3" type="text" class="form-control common_disable" name="data_consegna3" placeholder="Data Consegna3" /><br>
</div>

Please check above solution. It will enable input box at initial level. when you select one value, then it will disable input box.

Upvotes: 1

Related Questions