我有一个比萨饼浇头的选项列表,并且想将用户输入的内容保存为变量。由于通常大多数人会选择多个浇头,因此如何将输入作为单个变量捕获?
<p class="selectors">Toppings:</p>
<input type="radio" name="cheese" value="cheese">Cheese<br>
<input type="radio" name="pepperoni"
value="pepperoni">Pepperoni<br>
<input type="radio" name="sausage"
value="sausage">Sausage<br>
<input type="radio" name="onions" value="onions">Onions<br>
<input type="radio" name="greenPeppers"
value="greenPeppers">Green Peppers<br>
$(document).ready(function(event){
$("#mainForm").submit(function(event){
var toppings = $('????').val();
event.preventDefault();
});
});
答案 0 :(得分:1)
第一件事。您选择单选按钮的方式是错误的。就像复选框一样。所有单选按钮的名称都应该只有一个。
其次,以这种方式使用类或名称选择器:
$(document).ready(function(event) {
$("#mainForm").submit(function(event) {
var toppings = "Nothing selected!";
if ($(".flavour:checked").length > 0)
toppings = $(".flavour:checked").val();
console.log(toppings);
event.preventDefault();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="mainForm">
<p class="selectors">Toppings:</p>
<input type="radio" name="flavour" class="flavour" value="cheese">Cheese<br />
<input type="radio" name="flavour" class="flavour" value="pepperoni">Pepperoni<br />
<input type="radio" name="flavour" class="flavour" value="sausage">Sausage<br />
<input type="radio" name="flavour" class="flavour" value="onions">Onions<br />
<input type="radio" name="flavour" class="flavour" value="greenPeppers">Green Peppers<br />
<input type="submit" />
</form>
否则,如果需要多种选择,请使用.map()
:
$(document).ready(function(event) {
$("#mainForm").submit(function(event) {
var toppings = "Nothing selected!";
if ($(".flavour:checked").length > 0)
toppings = $(".flavour:checked").map(function () {
return $(this).val();
}).get().join();
console.log(toppings);
event.preventDefault();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="mainForm">
<p class="selectors">Toppings:</p>
<input type="checkbox" name="cheese" class="flavour" value="cheese">Cheese<br />
<input type="checkbox" name="pepperoni" class="flavour" value="pepperoni">Pepperoni<br />
<input type="checkbox" name="sausage" class="flavour" value="sausage">Sausage<br />
<input type="checkbox" name="onions" class="flavour" value="onions">Onions<br />
<input type="checkbox" name="greenPeppers" class="flavour" value="greenPeppers">Green Peppers<br />
<input type="submit" />
</form>