views:

36

answers:

2

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 element. 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?

A: 

1) remove binding;

2) make changes;

3) restore binding.

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

kpower
A: 

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

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


$.get("file.php", {x: x, y: y}, function(text)
{
$("select[name='dropdown_name']").data('changedByAjax', true).html(text).removeAttr("disabled"); // make note that we changed the value by ajax
    if (!$("select[name='dropdown_name'] option.selected").length)
    {
        $("select[name='dropdown_name'] option[value='1']").attr("selected", "selected");
    }
    $("#_inputfield").removeAttr("disabled");
});

I added .data('changedByAjax', true) into your ajax call and checked for .data('changedByAjax') in your change event (Also reset the value in the changed event). This is less overhead than unbinding and rebinding.

Dan Heberden