Javascript .on("change" only works when change manually [jsFiddle]

934 Views Asked by At

I have made a jsFiddle with all the data and information about the problem. I think there is easier to understand what's going on:

Please take a look:

http://jsfiddle.net/lukinhasb/GuZq2/

$("#estado").val(unescape(resultadoCEP["uf"]));

Mask only changes when you manually select the option. When javascript increments the field with the same data, it doesn't changes the mask.

    $("#estado").on("change", function() {
         if ($(this).val() == 'SP') {
             $("#celular_pessoa_fisica").mask("(99) 99999-9999");
                 } else {
             $("#celular_pessoa_fisica").mask("(99) 9999-9999");
             }
3

There are 3 best solutions below

1
On BEST ANSWER

That's how it's intended to work, but you can trigger the change event yourself when you set the value via JS:

$("#estado").val(unescape(resultadoCEP["uf"])).trigger('change');
1
On

When you change a field with javascript, it wont trigger the change event automatically. With jQuery, you can trigger change with $elem.change()

1
On

You can trigger a Change on the input so that your function is called:

$("#estado").val(unescape(resultadoCEP["uf"])).trigger("change");

More information:

  1. jQuery Trigger