javascript - 如何通过回车键验证答案?

标签 javascript jquery html validation

我创建了一个输入框,使用tab键验证,但需要在按下回车键后验证。

enter image description here

在这里,只有在我输入正确答案然后按 Tab 键后,才会显示刻度符号。然后它转到下一个输入框并进行验证。

但是,当我输入正确答案并在输入框内按下回车键时,需要进行验证。

为此,我尝试了这个 JS 代码:

$(document).keypress(function(e) {
  if(e.which == 13) {
    checktxt(h,v,w,c)
  }
});

function checktxt(h,v,w,c) {
  var th=$("#"+h).val();
  var tv=$("#"+v).val();
  if(th.toLowerCase()==tv.toLowerCase()) {
    $( "."+c ).show();
    $( "."+w ).hide(); 
  } else if(tv.toLowerCase()=="") {
  } else {
    $( "."+c ).hide();
    $( "."+w ).show();
  }
}

但是当我按下回车键时它也没有得到验证。

我的 HTML 代码是

<div>
  <input id="texthidden1" type="hidden" value="877" />
  <input id="textvisible1" type="text" value="" onblur="javascript:checktxt('texthidden1','textvisible1','wrong1','correct1');" />
  <div class="wrong1"><img src="../images/smallwrong.png"/></div>
  <div class="correct1"><img src="../images/smallgreen.png"/></div>
</div>

enter image description here

我还需要在删除输入框的内容时让刻度图像消失。

最佳答案

你的代码的问题在于你的按键监听器中的这一部分

checktxt(h,v,w,c) 

h、v、w 和 c 在这里是未定义的,因为 onblur 事件的代码工作正常并且你想在输入键时复制相同的代码,你需要在你的按键事件中定义这些变量。

如果您检查 html ,您会将所有元素的 ID 传递给 JS 中的 checktxt 函数。

在按键监听器中也做同样的事情。

 $(document).keypress(function(e) {
    if(e.which == 13) {
    checktxt('texthidden1','textvisible1','wrong1','correct1')
    }
 });

$(document).keypress(function(e) {
  if (e.which == 13) {
    checktxt('texthidden1', 'textvisible1', 'wrong1', 'correct1')
  }
});

function checktxt(h, v, w, c) {
  var th = $("#" + h).val();
  var tv = $("#" + v).val();
  if (th.toLowerCase() == tv.toLowerCase()) {
    $("." + c).show();
    $("." + w).hide();
  } else if (tv.toLowerCase() == "") {} else {
    $("." + c).hide();
    $("." + w).show();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input id="texthidden1" type="hidden" value="877" />
  <input id="textvisible1" type="text" value="" onblur="javascript:checktxt('texthidden1','textvisible1','wrong1','correct1');" />
  <div class="wrong1">
    <img src="../images/smallwrong.png" />
  </div>
  <div class="correct1">
    <img src="../images/smallgreen.png" />
  </div>
</div>

关于javascript - 如何通过回车键验证答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41972712/

相关文章:

javascript - Ajax 调用后更改 Div 的高度

javascript - jQuery - 在表中使用 (this) 进行滑动切换

javascript - 在 d3 中的图表上渲染之前简化一条线

jquery - 使用 jQuery 声明包含事件节点列表的变量

html - CSS 悬停无法按预期工作

javascript - 可拖动滚动和移动设备上的潜在问题

javascript - 通过video.js从html隐藏视频源src

javascript - JQuery Ajax 请求到 http ://pastebin. com/raw.php

javascript - 在 Debian 机器上构建 V8 时出现奇怪的错误

javascript - 使用jquery和ajax从html字符串中的div获取值