将值从焦点传递到模糊函数的最佳方式



我正在尝试将函数从焦点函数传递到模糊函数。如果值相同,我不必运行额外的验证。如果值不同,那么我会发送ajax调用,并确保数据库中不存在该值。一种方法是使用全局变量。有没有其他方法可以通过JavaScript/JQuery实现这一点?以下是示例:

var defaultNumber;
$(".check-number").focus(function() {
defaultNumber = $(this).val();
}).blur(function() {
var currNumber = $(this).val();

if(currNumber !== defaultNumber){
console.log('Send request...');
/*
Ajax call that checks if value already exist in database.
*/
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input type="text" class="form-control check-number" name="frm_number" id="frm_number" maxlength="2" pattern="[a-zA-Z0-9]{2}" title="Number field allows alphanumeric characters only (must be two characters length) - no other special characters" placeholder="Example: 07" value="99"
required>
</div>

您可以在焦点上将旧值保存为数据属性,并将当前值与模糊时的数据属性进行比较。

var defaultNumber;
$(".check-number").focus(function() {
$(this).attr('data-prev', $(this).val());
}).blur(function() {
var currNumber = $(this).val();

if(currNumber !== $(this).attr('data-prev')){
console.log('Send request...');
/*
Ajax call that checks if value already exist in database.
*/
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input type="text" class="form-control check-number" name="frm_number" id="frm_number" maxlength="2" pattern="[a-zA-Z0-9]{2}" title="Number field allows alphanumeric characters only (must be two characters length) - no other special characters" placeholder="Example: 07" value="99"
required>
</div>

无需存储,有defaultValue

var defaultNumber;
$(".check-number").blur(function() {
console.log(this.defaultValue!==this.value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input type="text" class="form-control check-number" name="frm_number" id="frm_number" maxlength="2" pattern="[a-zA-Z0-9]{2}" title="Number field allows alphanumeric characters only (must be two characters length) - no other special characters" placeholder="Example: 07" value="99"
required>
</div>

相关内容

  • 没有找到相关文章

最新更新