[英]Correct way to validate input of a select element
What is the correct way to validate if an option is selected on a dropdown? 验证是否在下拉列表中选择了一个选项的正确方法是什么? I have some select elements (fieldset) which are set to display none and others that are visible.
我有一些选择元素(字段集),这些元素设置为不显示,而其他元素则可见。 I want to validate only the ones that are visible, otherwise the form won't submit.
我只想验证可见的,否则表单将不会提交。
For Example: 例如:
<fieldset id="a1_1">
<select name="a1_1">
<option value="" selected="selected">Select Age</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</fieldset>
<fieldset id="a1_2" style=" display: none;">
<select name="a1_2">
<option value="" selected="selected">Select Age</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</fieldset>
<fieldset id="a2_1">
<select name="a2_1">
<option value="" selected="selected">Select Age</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</fieldset>
<fieldset id="a2_2" style=" display: none;">
<select name="a2_2">
<option value="" selected="selected">Select Age</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</fieldset>
I was trying something like this without any luck: 我正在尝试这样的事情,没有任何运气:
var x = document.forms["x"]["a1_1"].value;
if (x == null || x == "")
{
alert("Age must be selected");
return false;
}
Using jquery your could try something like below : 使用jquery,您可以尝试如下操作:
if ($("select[name=a1_1]").val().length <= 0)
{
alert("Age must be selected");
return false;
}
and use same for others, this will fix your issue. 并将其用于其他人,这将解决您的问题。
I would do something like this: 我会做这样的事情:
<fieldset id="a1_1">
<select name="a1_1" errorMessage="Age must be selected">
<option value="0" selected="selected">Select Age</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</fieldset>
//Catch submit form event
$('form').submit(function(){
//Go through all select elements of the form
$(this).find('select').each(function(){
//Validate the selected value
if($(this).val() === "0")
{
//Display the defined error message if needed
var msg = $(this).attr('errorMessage');
alert(msg);
//And return false to invalidate the form submission
return false;
}
});
});
它不起作用,因为您有两个id / name为a1_1
,请尝试给字段集赋予不同的id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.