在以下函数中,我尝试验证用户是否选择了适当的选择值。当我运行脚本时,警报弹出框显示“未定义”。我需要使用元素的名称而不是 ID 来获取元素。
Sort table in =
<select name="SortIn">
<option value="Please Choose">Please Choose</option>
<option value="asc">Ascending order</option>
<option value="desc">Descending order</option>
</select>
<input type="submit" name="submit" value="Submit" onclick="return validateForm()"/>
</form>
<script type="text/javascript">
/* <![CDATA [ */
function validateForm()
{
//Validates that form elements are not empty
var test = document.getElementsByName('SortIn').value;
alert(test1);
if(test1 == null || test == "")
{
alert("Please select sorting order");
return false;
}
else
{
return true;
}
}
/* ]]> */
</script>
最佳答案
document.getElementsByName('SortIn')
返回一个节点列表。您需要像这样获取该节点列表的第一个元素:
var test = document.getElementsByName('SortIn')[0].value;
关于javascript - 通过名称访问元素时未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20472712/