如何在jquery函数中验证输入字段?

时间:2016-11-10 11:22:44

标签: javascript jquery twitter-bootstrap

我的输入字段不是表格

<input type="text" class="form-control" id="ruling-value" required>

和按钮

<button id="addButton" type="button" class="btn btn-primary">add</button>

$('#addButton').click(function () {
        var values = $("#ruling-value").val().split(',');
        //some code
        }
    });

我希望在调用按钮onClick方法时验证ruling-value字段。如果字段为空,我想要显示工具提示或有关它的消息。我该怎么办?

2 个答案:

答案 0 :(得分:1)

简单地添加if(),同时验证nullempty。我使用引导警报框更新了我的答案

使用bootstrap更新

$('#addButton').click(function () {
    $(".alert").hide()
       if($("#ruling-value").val())
         {
     $(".alert-success").show()
        }
  else{$(".alert-warning").show()}
    });
.alert{display:none}
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="ruling-value" required>


<button id="addButton" type="button" class="btn btn-primary">add</button>
 <div class="alert alert-warning">
    <strong>Warning!</strong> This alert box could indicate a warning that might need attention.
  </div>
<div class="alert alert-success">
    <strong>Success!</strong> This alert box could indicate a successful or positive action.
  </div>

答案 1 :(得分:0)

您可以尝试这样做,您必须验证您的values,例如它不是空的而不是空的

$(document).ready(function(){
  $('#addButton').click(function () {
       var values = $("#ruling-value").val().split(',');
       if(values != '' && values  != null)
       {
           //Your code
        }else{
            alert("Required")
            return false;
         }
    });
});
<input type="text" class="form-control" id="ruling-value" required>
<button id="addButton" type="button" class="btn btn-primary">add</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>