我花了几天时间研究这个(包括查看这个网站),我不明白该怎么做。
我试图让JavaScript验证除默认空白选择之外的其他选项。
每次代码进入选择列表时,它会弹出窗口警报,但不会检查是否有任何选择。即使我选择了某些内容,弹出警报消息,然后继续执行代码,以便从未填写的字段中弹出其他错误警报。
我想知道是否选择了某些内容。如果是,则没有错误消息。如果没有选择任何内容,那么我希望只显示此警报消息。
这是与此列表(在标题中)
有关的Javascript函数function selectB() {
x = 0;
if (document.getElementById("mSQ").checked) {
x++;
}
if (document.getElementById("pSQ").checked) {
x++;
}
if (document.getElementById("cSQ").checked) {
x++;
}
if (x == 0) {
window.alert('You must select a Security Question');
mSQ.focus();
return false;
}
}
这是HTML
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question">
<option value = "d" id = "default" ></option>
<option value = "m" id = "mSQ" >What is your Mother's maiden name?</option>
<option value = "p" id = "pSQ" >What is the name of your pet?</option>
<option value = "c" id = "cSQ" >What is your favorite color?</option>
</select></p>
请帮助,我已经坚持这么久了。
答案 0 :(得分:1)
.checked
用于复选框和单选按钮。它不用于选择选项。您可以使用.value
获取所选选项的值。
使用:
var sec_question = document.getElementByName('Security Question')[0];
if (sec_question.value == 'd') {
window.alert('You must select a Security Question');
sec_question.focus();
return false;
}
您还可以使用HTML5 required
属性,以便浏览器自动执行检查。要使用它,默认选项应该为空值。
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question" required>
<option value = "" id = "default" ></option>
<option value = "m" id = "mSQ" >What is your Mother's maiden name?</option>
<option value = "p" id = "pSQ" >What is the name of your pet?</option>
<option value = "c" id = "cSQ" >What is your favorite color?</option>
</select></p>
答案 1 :(得分:0)
在change
元素上为select
事件添加eventlistener。让该处理程序只需检查selectedIndex
元素的select
(&gt; 0 =&gt;选择的内容)。对submit
元素所在的form
的{{1}}事件执行相同的操作。
select
// assign handlers
document.querySelector('#sq').addEventListener('change', check);
document.querySelector('#testform').addEventListener('submit', check);
function check(e) {
var selector = document.querySelector('#sq');
Helpers.logClear();
Helpers.log2Screen('<b>',
selector.selectedIndex > 0
? 'Selection ok'
: 'Please <i>do</i> select an option',
'</b> (from ',
/form/i.test(this.nodeName) ? 'submit' : 'change',
')');
return selector.selectedIndex > 0;
}
function submit() {
Helpers.log2Screen('we are ok');
}
答案 2 :(得分:0)
您实际需要查看的是选择是否有值。
以下是修改后的代码编辑。
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question" id="securityQuestion">
<option></option>
<option value="m">What is your Mother's maiden name?</option>
<option value="p">What is the name of your pet?</option>
<option value="c">What is your favorite color?</option>
</select>
<input type="button" value="Click to Check" onClick="checkDropdown(1)" />
</p>
<script>
function checkDropdown () {
var securityQuestionElement = document.getElementById('securityQuestion');
if(!securityQuestionElement.value) {
window.alert('You must select a Security Question');
securityQuestionElement.value = 'm'
return false;
}
}
</script>