j. Cup j. Cup - 6 months ago 12
HTML Question

How to properly disable and enable input field by option in HTML & JQUERY

How do I properly disable and enable form elements using jquery. I need to enable an input ("#byremaining") when I click on the "remaining" option. When i click the other options the input ("#byremaining") should be disabled again.



<html>

<head>
<script src="jq.js"></script>

<script>
$(document).ready(function() {
$('#byremaining').attr('disabled','disabled');
});

$(function(){

$('#remaining').click(function(){
$('#byremaining').removeAttr('disabled');
});

});
</script>

</head>
<body>
Sort by:
<select name="plaats" id="plaats">
<option value="plaats1">plaats1</option>
<option value="plaats2">plaats2</option>
<option value="plaats3">plaats3</option>
<option value="plaats4">plaats4</option>
<option value="remaining" id="remaining">remaining</option>
</select>
<br/>
date range:<br/>

Remaining:<input type="text" value="" name="byremaining" id="byremaining"></input><br/>

</body>

</html>





The remove attribute won't work now and i haven't created the disabled again.

Answer

$(document).ready(function() {
  $('#byremaining').prop('disabled', true); //use prop

  $('#plaats').change(function() {
    var selected = $('option:selected', this).attr('id')
    if (selected == 'remaining') { //if selected option is remaining 
      $('#byremaining').prop('disabled', false); //use prop
    } else {
      $('#byremaining').prop('disabled', true); //use prop
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sort by:
<select name="plaats" id="plaats">
  <option value="plaats1">plaats1</option>
  <option value="plaats2">plaats2</option>
  <option value="plaats3">plaats3</option>
  <option value="plaats4">plaats4</option>
  <option value="remaining" id="remaining">remaining</option>
</select>
<br/>date range:
<br/>Remaining:

<input type="text" value="" name="byremaining" id="byremaining"></input>
<br/>

  1. Use change event for select
  2. Use .prop()
Comments