This question already has an answer here:
I am building an application that allows users to choose pizza toppings by checking/unchecking checkboxes. The maximum I would like them to be able to select is 3 checkboxes. Once they select 4, I would like to send an alert to the user and deselect the last_checked checkbox. I have tried the following code to access the value of the most recent checked checkbox:
$("#Pizza #id_toppings").change(function() {
var last_checked = $("#Pizza #id_toppings input[name='toppings']:checked").val()
alert("The checkbox: '" + last_checked + "' changed");
});
Unfortunately, this only returns the value of the lowest checked box. Any ideas how I can get it to return the last_checked box? Example form is below.
<form action="/cart/" method="post" id="Pizza">
<input type="hidden" name="csrfmiddlewaretoken" value="hmgXKE0ximQjeAvhcSpLPa4WvL7dtUHW76D41WAgxMyzoBzTpzjeAMVuA99P3kSD">
<input type="hidden" value="Pizza" name="menu_item" id="menu_item" />
<p><label for="id_style">Style:</label> <select name="style" required id="id_style">
<option value="" selected>---------</option>
<option value="1">Regular</option>
<option value="2">Sicilian</option>
</select></p>
<p><label for="id_size">Size:</label> <select name="size" required id="id_size">
<option value="" selected>---------</option>
<option value="1">Small</option>
<option value="2">Large</option>
</select></p>
<p><label for="id_is_special">Gluten Free Dough:</label> <input type="checkbox" name="is_special" id="id_is_special"></p>
<p><label for="id_num_toppings">Number of Toppings:</label> <input type="number" name="num_toppings" required id="id_num_toppings"></p>
<p><label>Toppings:</label> <ul id="id_toppings">
<li><label for="id_toppings_0"><input type="checkbox" name="toppings" value="1" id="id_toppings_0">
Pepperoni</label>
</li>
<li><label for="id_toppings_1"><input type="checkbox" name="toppings" value="2" id="id_toppings_1">
Sausage</label>
</li>
<li><label for="id_toppings_2"><input type="checkbox" name="toppings" value="3" id="id_toppings_2">
Mushrooms</label>
</li>
<li><label for="id_toppings_3"><input type="checkbox" name="toppings" value="4" id="id_toppings_3">
Onions</label>
</li>
<li><label for="id_toppings_4"><input type="checkbox" name="toppings" value="5" id="id_toppings_4">
Ham</label>
</li>
<li><label for="id_toppings_5"><input type="checkbox" name="toppings" value="6" id="id_toppings_5">
Canadian Bacon</label>
</li>
<li><label for="id_toppings_6"><input type="checkbox" name="toppings" value="7" id="id_toppings_6">
Pineapple</label>
</li>
</ul></p>
<h5 id='price_indicator'>Price: $--.--</h5>
<input type="submit" value="Add Pizza to Cart" />
</form>
Aucun commentaire:
Enregistrer un commentaire