我们如何使用jquery / javascript插件在文本框下面显示错误消息?

时间:2016-05-20 08:31:43

标签: javascript html css

我正在尝试在" edit-first-name"下方显示错误消息。领域。但它没有显示错误消息。有人可以告诉我哪里出错吗?

<HTML>
    <div class= "col-xs-12 col-sm-12 col-md-6 highlight" > 
    <form id= "editform" class= "userform" method= "post"> 
    <label class= "bold" for= "first-name" > First Name: </label> 
    <input id= "edit-first-name" type= "text" name= "first-name" 
     maxlength= "128" class= "required"
    data-msg= "Please provide First Name" placeholder= "First Name" value= ""> 
    <div class="row md-gray-bg margin-md-0">
    <div class="col-xs-12 col-sm-12 col-md-12">
        <input id="cbot-save-ticket" tabindex="100" type="submit"
               class="button pull-right ignore"
               value="Save Ticket"/>
    </div>
</HTML>

Javascript:
<script type="text/javascript">
    document.getElementById("editform").addEventListener('submit',
    function  (event) {
    var focusSet = false;
    var fname = document.getElementById("edit-first-name");
    if(!(fname.value.length))
     {
       fname.after().html("<div class='msg-error' style='color:red;
       margin-bottom: 20px;'>Please enter email</div>");
        event.preventDefault();
        fname.focus();

     }
     });

1 个答案:

答案 0 :(得分:1)

after()是一种jquery方法。 after()方法在所选元素之后插入指定的内容,但您需要包含jquery才能使用它。 您可以简单地隐藏错误消息div,并在验证失败时显示错误消息div。以下是相同的代码段。

&#13;
&#13;
document.getElementById("editform").addEventListener('submit',
    function  (event) {
    var focusSet = false;
    var fname = document.getElementById("edit-first-name");
    if(!(fname.value.length))
     {
        document.getElementById('msg-error').style.display = 'block';
        event.preventDefault();
        fname.focus();

     }
     });
&#13;
<div class= "col-xs-12 col-sm-12 col-md-6 highlight" > 
    <form id= "editform" class= "userform" method= "post"> 
    <label class= "bold" for= "first-name" > First Name: </label> 
    <input id= "edit-first-name" type= "text" name= "first-name" 
     maxlength= "128" class= "required"
    data-msg= "Please provide First Name" placeholder= "First Name" value= ""> 
      <div class='msg-error' id='msg-error' style='color:red;margin-bottom: 20px;display:none;'>Please enter email</div>
    <div class="row md-gray-bg margin-md-0">
    <div class="col-xs-12 col-sm-12 col-md-12">
        <input id="cbot-save-ticket" tabindex="100" type="submit"
               class="button pull-right ignore"
               value="Save Ticket"/>
    </div>
&#13;
&#13;
&#13;