删除eventhandler似乎不起作用

时间:2017-01-19 14:59:58

标签: javascript jquery

我有下一个代码(代码不像这里复制的那样运行),我想用它来解决表单输入字段的错误。当场的焦点丢失时,将检查该字段。 ajax请求检查该字段是否允许该条目(基于查找表)。两个用户函数在输入字段周围设置和删除错误类。 当发生错误时,我希望错误字段具有整个表单的唯一焦点(用户必须在选择不同字段之前更正此字段)。 最后一个要求在代码中不起作用。焦点被交给田野。似乎我必须点击更多然后需要。

问题:我做错了什么?

$(document).ready(function() {
  var errors = [];
  //check value in lookup table with ajax
  $("body").on("blur", "input[data-table]", function() {
    var name = $(this).attr("id");
    var table = $("input[name=" + name + "]").data().table;
    var value = $(this).val();
    var len = value.length;
    //Only if an entry has been made in the field
    if (len > 0) {
      var jqxhr = $.post("/controller/lookup.php", {
        table: table,
        value: value
      }, function() {});
      //Done with the request	
      jqxhr.done(function(data) {
        var e = JSON.parse(data).error;
        if (e == "true") {
          //set error				
          setError(name);
          //prevent focus on other 
          $("body").on("click", "input", function(e) {
            if (!(e.target.id == name))
              $("input#" + name).focus();
          });
        } else {
          removeError(name);
          $("body").off("click", "input");
        }
      });
      //A failure has occured	
      jqxhr.fails(function(xhr, msg) {
        //TODO: exception handling  				  
      });
    }
    //if the field has been cleared remove error
    removeError(name);
  });

  function setError(name) {
    //Check if error already exists		
    if (!getErrors(name)) {
      var e = getErrorIndex(name);

      if (e > -1) errors[e].error = true;

      else errors.push({
        name: name,
        error: true
      });

      var span = "<span class=\"glyphicon glyphicon-exclamation-sign\" style=\"color: red; float: left\"></span>";
      //Decorate errors
      $("input#" + name).parent().addClass("has-error");
      $("input#" + name).after(span);

    };
  }

  function removeError(name) {
    var e = getErrorIndex(name);
    if (e > -1) {

      errors[e].error = false;

      $("input#" + name).parent().removeClass("has-error");
      $("input#" + name).next().remove();
    }
  }

  function getErrors(needle) {
    for (var i = 0; i < errors.length; i++) {
      if (errors[i].name === needle) return errors[i].error;
    }
    return false;
  }

  function getErrorIndex(needle) {
    for (var i = 0; i < errors.length; i++) {
      if (errors[i].name === needle) return i;
    }
    return -1;
  }
});
<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>

0 个答案:

没有答案