user1567553
user1567553

Reputation: 1

jquery change event keeps firing

I have to populate one select box (b) based on another one before (a), I used change event for this, but The change event keeps firing and the second select box keeps on populating itself, this way I am not able to select an item in the second select box, since whatever I select It repopulates itself and I see the very first entry selected in b.

$(document).ready(function () {
    $("*:first").change(function () {
        var b = document.forms[0].b;
        var a = document.forms[0].a.value;

        if (a != "") {
            var value = "";
            var par = 'c=' + a;

            $.ajax({
                url: "compute",
                data: par,
                type: "post",
                dataType: "text",
                async: false,
                success: function (data) {
                    value = JSON.decode(data);
                }
            });

            var options = "";

            for (k in value) {
                options = options + "<option value='" + value[k] + "'>" + k + "</option>" + "\n";
            }

            b.innerHTML = options;
        } else {
            b.innerHTML = '<option value="">-Select-</option>';
        }
    });
});

Upvotes: 0

Views: 533

Answers (1)

nbrooks
nbrooks

Reputation: 18233

Problem: You are correct that :first reduces the matched set to only the first item; however * matches everything, so *:first is actually selecting the <html> element (or other top-level element in your case). .change() is not intended for use with that element, so its default behavior is undefined -- but since the change event bubbles up to the top-level element from your <select> elements, it seems as if it is being triggered on both of them each time.

Solution: Bind your handler to the correct element. Also, don't make the request async: false, since this causes the browser to hang until the server responds. Instead, move the other code into the success callback:

$(document).ready(function() {
    var b = $('select:last');
    $("select:first").change(function() {
        var $this = $(this);
        var a = $this.val();

        if (a) {
            var par = 'c=' + a;
            $.ajax({
                url: "compute",
                data: par,
                type: "post",
                dataType: "text",
                //async: false,
                success: function(data) {
                    var value = JSON.decode(data);
                    var options = "";
                    for (k in value)
                        options += "<option value='" + value[k] + "'>" + k + "</option>";

                    b.html(options);
                }
            });
        }
        else {
            b.html('<option value="">-Select-</option>');
        }
    });
});​

Upvotes: 1

Related Questions