javascript - 简单的 javascript 验证表单,但我对 JS 完全陌生

标签 javascript validation

我有一个博客,我想在其中使用小型 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.')
  }
}

如果您希望函数在显示警报后返回 truefalse,可以按如下方式操作:

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/

相关文章:

ruby-on-rails - 如何为同一个 :if condition? 组合多个 Rails 验证

angular - 在 Angular 中比较自定义验证器中的值

javascript - 每次渲染react时刷新组件状态

javascript - 为什么允许独立代码块?

javascript - 验证 ng-repeat Angular 中的项目

javascript - 当有数据库调用时,调用验证 Jscript 函数的正确方法是什么?

针对 json/array 的 jQuery 文本字段验证

javascript - 仅在 Firefox 中表格超出字段集边界

javascript - 为什么 <Route component={Menu}/> 而不是 <Menu/>?

javascript - 如何检测小书签中的键盘修饰符?