I would like to create an option in a form like
[] I would like to order a [selectbox with pizza] pizza
where selectbox is enabled only when checkbox is checked and disabled when not checked.
I come up with this code:
<form>
<input type="checkbox" id="pizza" name="pizza" value="yes"> <label for="pizza">
I would like to order a</label>
<select name="pizza_kind">
<option>(choose one)</option>
<option value="margaritha">Margaritha</option>
<option value="hawai">Hawai</option>
</select>
pizza.
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
var update_pizza = function () {
if ($("#pizza").is(":checked")) {
$("#pizza_kind").removeAttr("disabled");
}
else {
$("#pizza_kind").prop('disabled', 'disabled');
}
};
$(update_pizza);
$("#pizza").change(update_pizza);
</script>
I tried various methods how to set disabled attribute using .prop()
, .attr()
, and .disabled=
. However, nothing happens. When applying to a <input type="checkbox">
instead of <select>
, the code works perfectly.
How to disable/enable <select>
using jQuery?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…