I've been trying to disable a form element using jquery, as per the example in the FAQ
Here is my attempt so far.
<script src="jquery-1.8.2.js"></script>
<form name="myForm" action ="process.php" method ="post" >
<p>Room type:<br />
<input type="radio" name="roomtype" value="mdorm" onClick="$('#roomnumber').attr('disabled','disabled')">Mixed Dorm<br>
<input type="radio" name="roomtype" value="fdorm" onClick="$('#roomnumber').attr('disabled','disabled')">Female Dorm<br>
<input type="radio" name="roomtype" value="room">Private Room<br>
</p>
<p>Room number<br />
<select name="roomnumber">
<option value="1">1</option>
<option value="2">2</option>
</select>
However, clicking any radio button never results in the drop downl list being disabled. I've followed the example essentially verbatim, so I'm not sure where I've gone wrong here.
You are using ID selector, but your select element doesn't have ID attribute:
<select id="roomnumber" name="roomnumber">
As of jQuery 1.6 for enabling/disabling form elements(or modifying other properties) prop method should be used instead of attr method, change your markup to:
<p>Room type:<br />
<input type="radio" name="roomtype" value="mdorm">Mixed Dorm<br>
<input type="radio" name="roomtype" value="fdorm">Female Dorm<br>
<input type="radio" name="roomtype" value="room">Private Room<br>
</p>
And you can code:
$(function(){ // document ready handler
$('input[name="roomtype"]').change(function(){ // listen to the change event
// disable the select element if value of radio group is not 'room'
$('#roomnumber').prop('disabled', this.value !== 'room')
})
})
http://jsfiddle.net/Er8zX/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With