Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery detect textbox value change NOT based on user input

Let's say you have a simple Text Box and button on your page. Clicking on the button will update the textbox value:

HTML:

<input type="text" id="myText" val="" />
<input type="button" id="myBtn" value="Change TextBox Value" />

jQuery:

$("#myBtn").on('click', function() {
   $("#myText").val('adsf');
})

I'd like to add an event listener for the change event of the textbox, like so:

$('#myText').on('change', function(){
    alert('Changed!')
});

That alert does not get triggered when you click the button but it does get triggered when you manually change the textbox value and focus out of it.

I know you can add $("#myText").trigger('change') to the onclick event of the button, but I wish to only accomplish this by adding an event listener to the textbox.

jsfiddle

Thanks

like image 803
Sammy Avatar asked Sep 08 '25 16:09

Sammy


1 Answers

There is no such event supported. The only thing you can try is to set interval or timeout to check if the value was changed (using data to store temporary value):

var $myText = $("#myText");

$myText.data("value", $myText.val());

setInterval(function() {
    var data = $myText.data("value"),
        val = $myText.val();

    if (data !== val) {
        $myText.data("value", val);
        alert("changed");
    }
}, 100);

DEMO: http://jsfiddle.net/xZcAr/1/

like image 105
VisioN Avatar answered Sep 10 '25 05:09

VisioN