首页 > 解决方案 > 如何在更改时验证输入字段并向用户显示消息?

问题描述

我有输入字段,用户应在其中输入系统 ID。用户输入系统 ID 验证后应触发。如果系统 ID 有效,则将 ajax 请求发送到服务器。如果系统 ID 无效,用户应该会看到该消息。我在这个项目中使用 JQuery 和 Bootstrap 3.3.7。这是我的代码示例:

$('#system_id').on('change', getInfo);

function getInfo(e) {
  var fldObj = $(this),
    fldVal = fldObj.val();

  if (fldVal.length > 0 && fldVal.length <= 8 && Number.isInteger(Number(fldObj.val()))) {
    //Send Ajax Request
    console.log('Send request for System ID: ' + fldVal);
  } else {
    // Show message to the user.
    if (fldVal.length === 0) {
      fldObj.parent().removeClass('has-error has-feedback');
      $('#symbol-error').remove();
    } else {
      console.log('Invalid System ID');
      fldObj.parent().addClass('has-error has-feedback').append('<span id="symbol-error" class="glyphicon glyphicon-remove form-control-feedback"></span>');
    }
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="form-group">
    <label class="control-label" for="system_id">System ID:</label>
    <input class="form-control" type="text" name="system_id" id="system_id" value="" placeholder="Enter System ID">
  </div>
</div>

到目前为止,我的逻辑工作正常,我正在检查用户输入值是否为整数以及它是否在 1 到 8 之间。如果可能,我想在输入字段内显示带有警报的消息(引导程序 3)。如果有人知道如何做到这一点,或者是否有更好的方法,请告诉我。谢谢你。

标签: javascriptjquerytwitter-bootstraptwitter-bootstrap-3validationmessage

解决方案


您可以在 console.log('Invalid System ID') 行之后添加到脚本中:

  fldObj.parent().addClass('has-error has-feedback');
  $('#system_id').val('Invalid System ID');

第一行将为输入着色。
第二行将插入您的消息。


推荐阅读