将值从焦点传递到模糊功能的最佳方法?

时间:2018-07-19 19:09:01

标签: javascript jquery focus blur

我正在尝试将功能从聚焦功能传递到模糊功能。如果值相同,则不必运行其他验证。如果值不同,那么我将发送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>

2 个答案:

答案 0 :(得分:1)

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

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>

答案 1 :(得分:1)

无需存储,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>