How to trigger jQuery change event in code
Asked Answered
D

5

235

I have a change event that is working fine but I need to get it to recurse.

So I have a function that is triggered on change that will "change" other drop downs based on a class selector (notice "drop downS", there could be more than one). This proxy change does not trigger the function and so fails. How can I get it to work?

Code

$(document).ready(function () {
    var activeDropBox = null;

    $("select.drop-box").change(function () {
        var questionId = $(this).attr("questionId");
        var selectedAnswer = $(this).val();
        activeDropBox = this;

        alert(this.questionId);

        $.ajax(
        {
            type: "POST",
            url: answerChangedActionUrl,
            data: { questionId: questionId, selectedValue: selectedAnswer },
            success: function (data) {
                SetElementVisibility(data.ShowElement, questionId);
            }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('XMLHttpRequest:' + XMLHttpRequest.responseText);
                alert('textStatus:' + textStatus);
                alert('errorThrown:' + errorThrown);
            }
        });
    });

    function SetElementVisibility(visible, questionId) {
        // I would like each child to then trigger the change event...
        $(".childOf" + questionId)[visible ? 'show' : 'hide']('slow');
        
        // Suggested code
        //$(".childOf" + questionId + " select").trigger("change");

        if (!visible) {
            $(".childOf" + questionId + " select").attr('selectedIndex', 0);
        }
    }
}

The suggestions so far seem to work, but as the change event triggers an ajax post it now seems to fail here. I'm going to play around with it but that is something for another question I feel.

Danais answered 22/11, 2010 at 15:48 Comment(4)
Provide some code so we can have a lookShields
How can we tell you how to get it to work, when you haven't shown us what it is?Incessant
I thought it was a simple concept and didn't feel code was required. The answers so far seem to have understood my explanation and so I am trying their solutions now. If I don't have any joy I'll post some code. My implementation is actually much more complex.Danais
Sorted it, was a problem with me changing the value after the ajax post. Thanks all for the help. The suggestions posted worked like a charm.Danais
V
508

Use the trigger() method

$(selector).trigger("change");
Valdovinos answered 22/11, 2010 at 15:51 Comment(5)
Is there any benefit to this over change()? Or is it just preference?Heffner
@JoshPinter no real benefit, more a preference. But definitely easier to abstract as a parameter than a method name.Valdovinos
Setting a value before actually triggering change event is the best way!!Bolshevism
Latest versions of jQuery (3 atm) will raise a warning when using the deprecated shorthand .change(). You should use .trigger('change') instead.Santinasantini
lets celebrate with 500 vote. dear john. its really help ful for meBotzow
L
54

For me

$('#element').val('...').change()

is the best way.

Note: .change() is deprecated in newer versions use .trigger('change') instead.

Lysol answered 30/1, 2015 at 11:50 Comment(5)
Yeah!, I like this oneEmeryemesis
Yes! it allows to choose option on the same time. I think your answer deserves to be the best here.Selfgoverned
This is the only way to trigger change event when programmatically altering the element's value.Antimatter
this is now deprecated. all best function essentials for development are getting deprecated... is it to make the developer keep learning new things always?Aile
@AmitShah Yeah I think .change() is deprecated in newer versions but .trigger('change') can be used just as well. I think the jQuery team is tired of making shortcuts for functions. It is also easier to find the right function to call when the documentation is a lot smaller.Homotaxis
T
21

The parameterless form of the change() method triggers a change event. You can write something like:

$(document).ready(function() {
    $("#yourInitialElementID").change(function() {
        // Do something here...
        $(".yourDropDownClass").change();
    });
});
Taishataisho answered 22/11, 2010 at 15:52 Comment(1)
this method is not getting Deprecated.Aile
R
15
$(selector).change()

.change()


.trigger("change")

Longer slower alternative, better for abstraction.

.trigger("change")

$(selector).trigger("change")
Ronaronal answered 19/1, 2016 at 2:0 Comment(0)
A
13

Use That :

$(selector).trigger("change");

OR

$('#id').trigger("click");

OR

$('.class').trigger(event);

Trigger can be any event that javascript support.. Hope it's easy to understandable to all of You.

Ararat answered 16/2, 2016 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.