Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...