How can I make .change() fire when the text changes without using input from a keyboard?

Viewed 141

I am using the jQuery.change() method and it works fine if I actually change something via the keyboard. Meaning to say that if I type something in the <input type="text"> field on my HTML page, then I change a character I mouse out the .change() method fires.

However, the problem now is that I am changing the text in the <input type="text"> via jQuery itself and now the .change() doesn't fire when the text changes cause it's not via an input keyboard. I have already tried various methods, but it doesn't seem to work. It only works when I do a change via keyboard inputs.

How can I make .change() fire when the text changes without using input from a keyboard?

This is the HTML part:

<label for="AddLongitude">*Longitude: </label>
<label id="Add_Long_Label" style="color:red"></label>
<input type="text" id="AddLongitude" name="Add_ServiceCompany" 
    placeholder="Tap on the map" maxlength="18" data-clear-btn="true"  readonly/>

<label for="AddLatitude">*Latitude: </label>
<label id="Add_Lat_Label" style="color:red"></label>
<input type="text" id="AddLatitude" name="Add_ServiceCompany" 
    placeholder="Tap on the map" maxlength="18" data-clear-btn="true" readonly/>

This is the jQuery part:

$("#AddLongitude").change(function () {
            if ($("#AddLongitude").val() == "") {
                $("#Add_Long_Label").text("This field is mandatory.");
                $("#Add_Lat_Label").text("This field is mandatory.");
            }
            else {
                $("#Add_Long_Label").text("");
                $("#Add_Lat_Label").text("");
            }
        });

This is the part where the value changes:

$("#AddLongitude").val(e.latlng.lng);
$("#AddLatitude").val(e.latlng.lat);

where e.latlng.lng or e.latlng.lat is the variable holding the values to be written.

1 Answers

You have to trigger change() function manually after changing the value since it is not an user input. change() method fire only user changed the value.

$("#AddLongitude").val(e.latlng.lng).change(); 
$("#AddLatitude").val(e.latlng.lat).change();
Related