javascript 如何使用 jQuery 在表单上以红色字体显示错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17989885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:21:15  来源:igfitidea点击:

How to display error messages in red font color on form using jQuery?

phpjavascriptjqueryerror-handlingsmarty

提问by PHPLover

I'm using PHP and smarty. I'm bit new to jQuery. I've written a function in jQuery and calling this function on form submit. Currently I'm showing the error message in alert. But the requirement is it should be displayed above the form and the field having error should get highlighted. The font colour should be red in both cases. For your reference I'm pasting my smarty template code(i.e form code).

我正在使用 PHP 和 smarty。我对 jQuery 有点陌生。我已经在 jQuery 中编写了一个函数并在表单提交时调用了这个函数。目前我在警报中显示错误消息。但要求是它应该显示在表单上方,并且应该突出显示有错误的字段。在这两种情况下,字体颜色都应该是红色。供您参考,我正在粘贴我的 smarty 模板代码(即表单代码)。

<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" >
  <tr>
    <td align="left" valign="top"><h3>Contact Lists >> {$bread_crumbs_text}</h3></td>
  </tr>
  <tr>
    <td valign="top">
      <table width="99%" border="0" cellpadding="0" cellspacing="0" class="manage_box" >
        <tr>
          <td>
            <div id="contact_list_import">
              <form name="manage_contact_list_import" id="manage_contact_list_import" action="contact_list_import.php" method="post">
                <input type="hidden" name="op" id="op" value="{$op}">
                <input type="hidden" name="contact_list_id" id="contact_list_id" value="{$contact_list_id}"> 
                <input type="hidden" name="form_submitted" id="form_submitted" value="yes"> 
                <table width="99%" border="0" cellpadding="5" cellspacing="5">
                  <tr>
                    <td colspan="3" class="errorMsg">{$error_msg.error_msgs}</td>
                  </tr>
                  <tr height="30" id="user_option">
                    <td width="300">
                       <input type="checkbox" id="users" name="users_choice" value="users"/>Users 
                    </td>
                    <td>&nbsp;<input type="checkbox" id="upload_from_file" name="users_choice" value="upload_from_file"/>Upload From File
                    </td>
                    <td>
                    <input type="checkbox" id="copy_paste_from_excel" name="users_choice" value="copy_paste_from_excel"/>Copy paste from excel
                    </td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <table border="0" width="80%" class="option_users">
                  <tr height="30">
                    <td align="left" width="80%" colspan="5">
                    <h4>Users</h4>
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="all_users" value="all_users"/>all users &nbsp;&nbsp;  
                    </td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <tr height="30">
                    <td align="left" width="20%">
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="registered_users" value="registered_users"/>Registered users &nbsp;&nbsp;  
                    </td>
                    <td valign="middle" align="left" width="10%"><b>From Date </b> : </td>
                    <td align="left" >&nbsp;<input type="text" style="width:100px;" class="inputfield" name="registered_users_from_date" id="registered_users_from_date" maxlength="10" width="20%"></td>
                    <td valign="middle" align="left" width="10%"><b>To Date </b> : </td>
                    <td>&nbsp;<input type="text" style="width:100px;" class="inputfield" name="registered_users_to_date" id="registered_users_to_date" maxlength="10" width="20%"></td> 
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <tr height="30">
                    <td align="left" width="20%">
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="logged_in_users" value="logged_in_users"/>Logged-in users &nbsp;&nbsp;  
                    </td>
                    <td valign="middle" align="left" width="10%"><b>From Date </b> : </td>
                    <td align="left" >&nbsp;<input type="text" style="width:100px;" class="inputfield" name="registered_users_from_date" id="logged_in_users_from_date" maxlength="10"></td>
                    <td valign="middle" align="left" width="10%"><b>To Date </b> : </td>
                    <td>&nbsp;<input type="text" style="width:100px;" class="inputfield" name="registered_users_to_date" id="logged_in_users_to_date" maxlength="10"></td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <tr height="30">
                    <td align="left" width="20%">
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="not_logged_in_users" value="not_logged_in_users"/>Not logged-in Users &nbsp;&nbsp;  
                    </td>
                    <td valign="middle" align="left" width="10%"><b>From Date </b> : </td>
                    <td align="left" >&nbsp;<input type="text" style="width:100px;" class="inputfield" name="not_logged_in_users_from_date" id="not_logged_in_users_from_date" maxlength="10"></td>
                    <td valign="middle" align="left" width="10%"><b>To Date </b> : </td>
                    <td>&nbsp;<input type="text" style="width:100px;" class="inputfield" name="not_logged_in_users_to_date" id="not_logged_in_users_to_date" maxlength="10"></td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <tr height="30">
                    <td width="300" colspan="5">
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="never_logged_in_users" value="never_logged_in_users"/>Never logged-in Users  
                    </td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <tr height="30">
                    <td width="300" colspan="1">
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="package_purchase" value="package_purchase"/>Package purchase  
                    </td>
                    <td align="left"  colspan="4">
                      <select name="test_pack_type_id" id="test_pack_type_id">
                      <option value="">All</option> 
                      {if $all_type}
                       {foreach from=$all_type item="type"}
                      <option value="{$type.package_type_id}">{$type.package_type_name}</option>
                       {/foreach}
                      {/if}
                 </select>
                  </td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                  <tr height="30">
                    <td width="300" colspan="5">
                    <input type="checkbox" class="user_checkbox" name="user_checkbox" id="try_demo_packages" value="try_demo_packages"/>Try demo packages  
                    </td>
                  </tr>
                  <tr><td colspan="5">&nbsp;</td></tr>
                </table>
                  <tr>
                    <td colspan="5" valign="top" align="center">
                      <input type="submit" name="submit_value" id="submit_value" value="{$submit_value}" class="submit">&nbsp;&nbsp;
                      <input type="button" name="back" id="back" value="{$cancel_value}" class="submit" onclick="javascript:window.location.href='{$control_url}modules/contact_list/contact_list.php'"/>
                    </td>
                  </tr>
                </table>
              </form>                       
            </div>
          </td>
        </tr>
      </table>
    </td>   
  </tr>             
</table>
{literal}
<script language="javascript" type="text/javascript">
$(function() {
    $( "#registered_users_from_date" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy'
    });
});

$(function() {
    $( "#registered_users_to_date" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy'
    });
});

$(function() {
    $( "#logged_in_users_from_date" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy'
    });
});

$(function() {
    $( "#logged_in_users_to_date" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy'
    });
});

$(function() {
    $( "#not_logged_in_users_from_date" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy'
    });
});

$(function() {
    $( "#not_logged_in_users_to_date" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy'
    });
});

$(function(){
  $(".user_checkbox").click(function(){ 
    if($("#all_users" ).is(":checked")) {
      $("#registered_users").removeAttr("checked");
      $("#logged_in_users").removeAttr("checked");
      $("#not_logged_in_users").removeAttr("checked");
      $("#never_logged_in_users").removeAttr("checked");
      $("#package_purchase").removeAttr("checked");
      $("#try_demo_packages").removeAttr("checked");
    } else if ($("#registered_users" ).is(":checked") || $("#logged_in_users" ).is(":checked") || $("#not_logged_in_users" ).is(":checked") || $("#never_logged_in_users" ).is(":checked") ||
        $("#package_purchase" ).is(":checked") || $("#try_demo_packages" ).is(":checked") )    {
        $("#all_users").removeAttr("checked"); }
    });
});

$(function(){
  $('.option_users').hide();    
  $("#users").click(function() {
    if($("#users").is(":checked"))
        $('.option_users').show();  
    else
        $('.option_users').hide();
  });
});

$("#submit_value").click(function(){
    if($('#user_option').find('input[type=checkbox]:checked').length == 0)
    {
      alert('Please select atleast one checkbox');
      return false;
    }
    if($("#users").is(":checked")) { 
      if($('.option_users').find('input[type=checkbox]:checked').length == 0) { 
        //alert(('input[type=checkbox]:checked').length);
        alert('Please select atleast one checkbox for user type');
        return false;
      }
    }
    return true;
});
</script>
{/literal}

回答by Adrian

$("#submit_value").click(function(){
    if($('#user_option').find('input[type=checkbox]:checked').length == 0)
    {
      $('.errorMsg').html('<span style="color:red">Please select atleast one checkbox</span>');
      return false;
    }
    if($("#users").is(":checked")) { 
      if($('.option_users').find('input[type=checkbox]:checked').length == 0) { 
        //alert(('input[type=checkbox]:checked').length);
       $('.errorMsg').text('<span style="color:red">Please select atleast one checkbox for user type</span>');
        return false;
      }
    }
    return true;
});

回答by Saranya Sadhasivam

Give a span tag at the top of the form

在表单顶部给出一个span标签

<span id="errorMsg"></span>

In Jquery, instead of alert give as

在 Jquery 中,而不是警报给出为

$('#errorMsg').css('color','red');
$('#errorMsg').html('Please select atleast one checkbox');

回答by HIRA THAKUR

if (error exist) {
  $errormsg = "<span style='color: red'>sometext</span>";
  $("#id").html($errormsg)
}

or you can also addClass.

或者你也可以addClass

//css
.error {
    color: red;
}

 //javascript
 if (error exist) {

      $("#id").addClass('error').html("sometext")
    }

addClass

添加类

回答by DynamicDeveloper

$("#submit_value").click(function(){
    if($('#user_option').find('input[type=checkbox]:checked').length == 0)
    {
      $("#user").html('Please select atleast one checkbox');
      return false;
    }
    if($("#users").is(":checked")) { 
      if($('.option_users').find('input[type=checkbox]:checked').length == 0) { 
        //alert(('input[type=checkbox]:checked').length);
        $("#user").html('Please select atleast one checkbox for user type');
        return false;
      }
    }
    return true;
});

at the top of or at the checboxes add divs with different id

在复选框的顶部或复选框中添加具有不同 id 的 div

<div id="user" style='color:red'></div>

回答by Mukesh Dabhi

$("#submit_value").click(function(){
  if($('#user_option').find('input[type=checkbox]:checked').length == 0)
    {
    $('.errorMsg').css({ 'color': 'red'});
    $('.errorMsg').html('Please select atleast one checkbox');
           return false;
    }
    if($("#users").is(":checked")) { 
      if($('.option_users').find('input[type=checkbox]:checked').length == 0) { 
        //alert(('input[type=checkbox]:checked').length);
        $('.errorMsg').css({ 'color': 'red'});
    $('.errorMsg').html('Please select atleast one checkbox for user type');


        return false;
      }
    }
    return true;
});

回答by Chococroc

Ok, some things I would do:

好的,我会做一些事情:

1- Don't link to an element id, instead, link the event to the form:

1- 不要链接到元素 id,而是将事件链接到表单:

$("#submit_value").click(function() {
$('form.validate').submit(function() {

With this, you'll have to add the class 'validate' to the html form. And by this way any submit button will check the form, even if you use jquery to trigger the form's submit, and you'll be able of reuse jquery code

有了这个,您必须将“验证”类添加到 html 表单中。通过这种方式,任何提交按钮都会检查表单,即使您使用 jquery 触发表单的提交,并且您将能够重用 jquery 代码

2- Use classes to add the style.With classes, you can easily define how will be the error element style:

2- 使用类来添加样式。使用类,您可以轻松定义错误元素样式:

input.error {
    background-color:red;
    border: 1px solid red;
}
select.error {
    border: 1px solid red;
}

And it's easy to append to an element a class than all an style.

并且很容易将一个类附加到一个元素而不是一个样式。

3 - Create a reserved space for your messages in the html, with the loaded message, hidden. It'll be easy to you to change the message you want to show, from PHP.

3 - 在 html 中为您的消息创建一个保留空间,隐藏加载的消息。您可以轻松地从 PHP 更改要显示的消息。

<tr>
    <td colspan="3" class="errorMsg">{$error_msg.error_msgs}</td>
</tr>

should contain something like:

应该包含以下内容:

<tr>
     <td colspan="3" class="errorMsg">
     <p id="errorIDelement">Error with input IDelement</p>
     <p id="errorUserCheck">Please select atleast one checkbox for user type</p>
     </td>
</tr>

Your jquery code, would be something like:

您的 jquery 代码将类似于:

$("form.validate").submit(function(e){
    $form = $(this);
    e.preventDefault(); 

    //Not selected checkbox:
    $errorChecks = $form.find('input[type=checkbox]:checked');

    if($errorChecks.length != 0) {
      $errorChecks.each( function(){
          // This would highlight error 
          $(this).addClass('error');
          // This would show error in your list
          $id = $(this).attr('id');
          $('#error'+$id ).show();              
      });
    } else if($("#users").is(":checked") && $('.option_users').find('input[type=checkbox]:checked').length == 0) { 
         $('.errorMsg .errorUserCheck').show();
         $("#users").addClass('error');
      } else {
      // If we arrived here, we have validated all, and can submit
      $form.submit(); 
    }
});

It's not checked, and a long answer, if you have any doubt, just post again, ;)

它没有经过检查,而且答案很长,如果您有任何疑问,请再次发布,;)