开发者

How to prevent JQuery change event from triggering when select's HTML is changed?

I have a select element that has a change event attached so that, when the user selects a new option, that text is placed into a corresponding input ele开发者_如何转开发ment. That's working fine:

$("select[name='" + dropdown_name + "']").live("change", function()
{
    text = $("select[name='" + dropdown_name + "'] option:selected").text();
    $("#" + inputfield).val(text);
});

However, when another select is changed, that select field's html is changed according to an AJAX request. When this happens, the selected value from the select element pre-HTML change is placed into the input field.

$.get("file.php", {x: x, y: y}, function(text)
{
$("select[name='dropdown_name']").html(text).removeAttr("disabled");
    if (!$("select[name='dropdown_name'] option.selected").length)
    {
        $("select[name='dropdown_name'] option[value='1']").attr("selected", "selected");
    }
    $("#_inputfield").removeAttr("disabled");
});

How do I prevent that particular function from occurring only when the HTML is changed?


1) remove binding;

2) make changes;

3) restore binding.

Or use some checked value (maybe, value of hidden input) - to reduce event binding changes.


You could log that the change was in the ajax control and access that in your change event..

(function(){
  var changedByAjax;
  $(document).on('change', 
                 "select[name='" + dropdown_name + "']", 
                 function() {
    var $select = $(this);
    // make sure the change wasn't by ajax
    if( !changedByAjax ) { 
      text = $select.find("option:selected").text();
      $("#" + inputfield).val(text);
    }
    changedByAjax = false; 
  });

  $.get("file.php", {x: x, y: y}, function(text) {
    var $select = $("select[name='dropdown_name']")
    $select.html(text).removeProp("disabled"); 

    // make note that we changed the value by ajax
    if ( !$select.find("option.selected").length ) {
      $select.find("option[value='1']").prop("selected", true);
    }
    $("#_inputfield").removeProp("disabled");
  });
}());

I added changedByAjax into your ajax call and checked for it in your change event (Also reset the value in the changed event). This is less overhead than unbinding and rebinding. Kept it private by putting it in an IIFE - the power of scope. However, this is way too DOM centric of an approach. But, alas, an answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜