Ravi Kumar Ravi Kumar - 21 days ago 7
jQuery Question

make an input text into read only when one value is selected from drop down list using jquery

i have one select box there in that options are,


  • none

  • current

  • future



if you select 'NONE' the all text box should be editable.
if you select 'current' the
class="current"
those text box should be editable and remaining should be only readonly.
similarly same like to future also. When i select future the future text boxes should be editable and remaining should be readonly



$('#cognizant').change(function(){
if(this.value == ""){
$('.current').prop('readonly',true);
} else{
$('.current').prop('readonly',false);
}
}).change();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="curator">
<tbody id="tableToModify">
<tr>
<td>
<select id="cognizant" class="discount-type" >
<option value="">none</option>
<option value="1">current</option>
<option value="2">future</option>

</select>
</td>
<td>
<input type="text" id="clientbi" class="current"/>
<input type="text" id="cognizantbi" class="current"/>
<input type="text" id="futurevsm" class="future" />
<input type="text" id="futuresymbols" class="future" />
</td>
</tr>
</tbody>
</table>




Answer

Let's change your javascript code only.

We need to use jQuery's change() function (documentation) and then validate the selected option.

The final code:

$('#cognizant').change(function(){

  var value = $(this).val();

  if(value == ''){
    // NONE
    $('#curator input[type="text"]').removeAttr('readonly');
  }
  else if(value == '1'){
    // CURRENT
    $('#curator input[type="text"]').attr('readonly', true);
    $('#curator .current').removeAttr('readonly');
  }
  else if(value == '2'){
    // FUTURE
    $('#curator input[type="text"]').attr('readonly', true);
    $('#curator .future').removeAttr('readonly');
  }

});

See it in action: https://jsfiddle.net/x5fdLqff/4/