如果用户在文本字段中输入特定的数字组合而不必提交表单,我希望显示通知。
例如:如果用户在Field#ExampleField1中键入1234或7890,页面将显示div#ExampleDiv1
我发现大量的表单验证示例都是在提交时发生但不是直播。
答案 0 :(得分:3)
已更新以回答评论中的问题
这样的事情可能会让你开始。
实时:
arr = ['4486','4716','5568'];
$('input').keyup(function(){
var tmp = this.value;
var fnd = false;
for (i=0; i<arr.length; i++){
if ( this.value.indexOf(arr[i])>-1 ) fnd = true;
}
if (fnd){
$('#msg').addClass('wow').slideDown('slow');
}else{
$('#msg').removeClass('wow').slideUp('slow');
}
});
.wow{background:yellow;color:brown;}
#msg{margin-top:10px;display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Watching for 4486, 4716, 5568:<br>
<input id="ExampleField1" type="text" />
<div id="msg">It's one of <em>THEM</em></div>
离开现场
$('input').blur(function(){
if (this.value.indexOf('1234') > -1) $(this).addClass('wow');
else $(this).removeClass('wow');
});
.wow{background:yellow;color:brown;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Watching for 1234: <input id="ExampleField1" type="text" />
或表格提交:
$('form').submit(function(){
if ( $('#ExampleField1').val().indexOf('1234') > -1) $('#ExampleField1').addClass('wow');
else $('#ExampleField1').removeClass('wow');
});
.wow{background:yellow;color:brown;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Watching for 1234: <input id="ExampleField1" type="text" />
答案 1 :(得分:2)
这将向您展示如何根据文本输入显示/隐藏元素 我使用正则表达式来提高效率和清晰度。我还测试了我的正则表达式here。
//Shorthand for $(document).ready();
$(function() {
//The numbers to search for in the string.
var numRegEx = /(4486|4716|5568)/;
var msg = $('#msg');
//Hide the message on load.
msg.hide();
var txt = $('#txt');
//Wire up the keyup event listener
txt.keyup(function(){
var val = $(this).val();
/*****
Using regular expressions is the most efficient way to do this.
You can check for additional numbers above by modifying
the regular expression.
******/
if (numRegEx.test(val)) {
msg.show();
//You can use other jQuery methods to show/hide the message.
/*
msg.slideDown();
msg.fadeIn();
*/
} else {
msg.hide();
/*
msg.slideUp();
msg.fadeOut();
*/
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="txt">Try entering text that contains 4486 OR 4716 OR 5568</label>
<br/>
<input type="text" id="txt" placeholder="Enter text here..." />
<div id="msg">
<b>Hello, world!</b>
</div>
答案 2 :(得分:0)
<form>
<input class="target" type="text" value="Field 1">
</form>
<button id="other">
Trigger the handler
</button>
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
$( "#other" ).click(function() {
$( ".target" ).change();
});
看这里:https://jsfiddle.net/ztvnwthk/
在这里:https://api.jquery.com/change/