我的输入字段不在表单中
<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
字段。如果字段为空,我想显示工具提示或有关它的消息。我该怎么做?
最佳答案
简单添加 if()
即可验证 null
和 empty
。我用 Bootstrap 警报框更新了我的答案
使用 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>
关于javascript - 如何验证jquery函数中的输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40526404/