Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

html - How to disable/enable select field using jQuery?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would like to use code like this:

<form>
  <input type="checkbox" id="pizza" name="pizza" value="yes">
  <label for="pizza">I would like to order a</label>
  <select id="pizza_kind" 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').prop('disabled', false);
    }
    else {
        $('#pizza_kind').prop('disabled', 'disabled');
    }
  };
  $(update_pizza);
  $("#pizza").change(update_pizza);
</script>

?Here is working example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...