我希望有人选择一个选项,但不是第一个选项-- Select --.
HTML
<select name = "sources" id = "brandname" required onblur = "selectText()" />
<option value = "select"> -- Select -- </option>
<option value = "referal"> Referal </option>
<option value = "justdial"> Justdial </option>
<option value = "sulekha"> Sulekha </option>
<option value = "website"> Website </option>
<option value = "others"> Others </option>
</select>
JS
if (document.getElementById("brandname").value == "select") {
alert("Please select the required value");
document.getElementById("brandname")[1].focus();
}
它执行警报消息,之后它移动到下一个字段。但它应该坚持下拉,直到并且除非选择值改变为任何其他值。
代码有什么问题? 提前谢谢!
答案 0 :(得分:1)
<强> HTML 强>
<select id="mySelect">
<option>v1</option>
<option>v2</option>
...
</select>
<强>的JavaScript 强>
var s = document.getElementById("mySelect");
使用
检查所选值s.options[s.selectedIndex].value // Keep this in mind
如果声明:
if(s.options[s.selectedIndex].value == "select") {
alert("A value is required!");
s.focus();
}
(没有[1]
的焦点:
document.getElementById("brandname").focus();
)
答案 1 :(得分:0)
只需从焦点声明中删除[1]
。由于getElementById
始终会返回单个对象。
var selectText =function(){
if(document.getElementById("brandname").value == "select") {
alert("Please select the required value");
document.getElementById("brandname").focus();
}}
<select name = "sources" id = "brandname" required onblur = "selectText()" />
<option value = "select"> -- Select -- </option>
<option value = "referal"> Referal </option>
<option value = "justdial"> Justdial </option>
<option value = "sulekha"> Sulekha </option>
<option value = "website"> Website </option>
<option value = "others"> Others </option>
</select>