Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger jQuery change event in code

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.

like image 343
4imble Avatar asked Nov 22 '10 15:11

4imble


People also ask

Does jQuery Val trigger change event?

When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.


1 Answers

Use the trigger() method

$(selector).trigger("change"); 
like image 156
John Hartsock Avatar answered Sep 22 '22 15:09

John Hartsock