我有一个博客,我想在其中使用小型 JS 文本区域验证。
基本上我想要它做的是检查某个字符串
“我要检查的字符串”。
我希望它验证这些确切的单词,如果不正确,我希望它说
不正确!您需要更多帮助吗?
但是当它正确时,我希望它说
正确!转到下一个问题。
我的问题是我没有任何 JS 经验,但我认为通过 stackoverflow 和 google 搜索已经得到了很大的帮助。但我没有得到我想要的输出.. 有人可以快速浏览一下并稍微调整一下吗?
function validateForm() {
var textarea = document.getElementById('textareabox');
var word = ('the string I want to check');
var textValue = textarea.value;
if (textValue.indexOf(word) != -1) {
alert('Correct! Go to the next question!)
} else {
return false
alert('Incorrect! Do you need more help? Try the hint button.')
}
}
<textarea id="textareabox" name="powershellarea"></textarea>
<button type="button" onclick="validateForm()">Validate</button>
最佳答案
您应该从 else block 中删除 return false;
。
通过该返回,代码会在警报执行之前退出函数,并且永远不会显示。
您还缺少字符串中的结束引号 '
。
function validateForm() {
var textarea = document.getElementById('textareabox');
var word = 'the string I want to check';
var textValue = textarea.value;
if (textValue.indexOf(word) != -1) {
alert('Correct! Go to the next question!')
} else {
alert('Incorrect! Do you need more help? Try the hint button.')
}
}
如果您希望函数在显示警报后返回 true
或 false
,可以按如下方式操作:
function validateForm() {
var textarea = document.getElementById('textareabox');
var word = 'the string I want to check';
var textValue = textarea.value;
if (textValue.indexOf(word) != -1) {
alert('Correct! Go to the next question!');
return true;
} else {
alert('Incorrect! Do you need more help? Try the hint button.');
return false;
}
}
关于javascript - 简单的 javascript 验证表单,但我对 JS 完全陌生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42325119/