1

.change call in jquery is not working when I change value through Javascript.

For example:

 $(document).ready(function () {
     $(function () {
         $("select#product").change(function () {
             if (document.all("fatcaSearchDO.bankId").disabled.value = true) {
                 fnFieldEnableClass(document.all("fatcaSearchDO.bankId"));
             }
             $.ajax({
                 type: 'GET',
                 url: 'ViewHistoryDataAction.do',
                 data: {
                     product: $(this).val()
                 },
                 dataType: 'JSON',
                 cache: false,
                 success: function (j) {
                     var options = '';
                     for (var k = 0; k < j.length; k++) {
                         options += '<option value="' + j[k] + '">' + j[k] + '</option>';
                     }
                     $("select#BankID").html(options);
                 }
             });
         });
     });
 });




<html:select name="ViewHistoryForm" property="fatcaSearchDO.bankId" styleClass="login-textbox" onchange="fnGlobalChange();" onclick="checkRadio('1')" onfocus = "checkRadio('1')" styleId="BankID" style="width=250">

<html:select name="ViewHistoryForm" property="fatcaSearchDO.product" styleClass="login-textbox" onchange="fnGlobalChange();" onclick="checkRadio('1')" onfocus = "checkRadio('1')" styleId="product" style="width=250">

Here when I try to change the drop down of "product" its calling action and the respective bank id values are populated. Now, when I try to change the value of "product" through javascript, for instance

<input type="button" onclick="changeProd()">

function changeProd(){
    document.all("fatcaSearchDO.product").value='CC';

}

the change function is not working.

Lundin
  • 195,001
  • 40
  • 254
  • 396

3 Answers3

1

when you change the value of a input field through javascript, the change event will not be fired.

You need to fire the change event manually

like

$("#fatcaSearchDO.product").trigger('change')

ex:

function changeProd(){
    $("#fatcaSearchDO.product").val('CC').trigger('change');
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
$(document).ready(function() {
  // Handler for .ready() called.
});

is equivalent to calling:

$(function() {
     // Handler for .ready() called.
});

Please use one or the other.

Mysteryos
  • 5,581
  • 2
  • 32
  • 52
0

Why not make the anonymous function inside the change into a separately defined function, so you can just do it like this:

function changeHandler(element) {
  // code code code
  value = element.val();
}

$(something).change(function() {
  changeHandler($(this));
});

// then when changing value with JS
var element = ... // select the element with javascript here
element.value='CC';
changeHandler($(element)); // just call the function everytime the value gets changed
Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32