【问题标题】:How to validate answer by enter key?如何通过输入键验证答案?
【发布时间】:2017-02-10 19:15:36
【问题描述】:

我创建了一个输入框,通过tab键进行验证,但是需要在按下回车键后进行验证。

这里,只有在我输入正确答案然后按 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>

我还需要在擦除输入框内容时使刻度图像消失。

【问题讨论】:

    标签: javascript jquery html validation


    【解决方案1】:

    您的代码的问题在于您的按键列表器中的这一部分

    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>

    【讨论】:

    • 擦除输入框的内容时,我还需要使刻度图像消失。
    • @Anitha 您可以在输入上绑定一个更改事件侦听器并检查该值是否为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2015-09-02
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多