Sammy
Sammy

Reputation: 3099

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

Upvotes: 27

Views: 30126

Answers (5)

Stefan Avramovic
Stefan Avramovic

Reputation: 1353

You can do something like this. Instead of listening for an input field listen to a change on div that gets updated att same time.

function trigger(){
setTimeout(function(){ 
document.getElementsByName("Thing")[0].value = 'hello'
document.getElementById('myDiv').innerHTML = document.getElementsByName("Thing")[0].value 

}, 3000);
}

trigger()
document.getElementById("myDiv").addEventListener('DOMSubtreeModified', (e)=>{
  console.log(e.target.innerHTML)
 
});
<input type="text" name="Thing" value="" />
<div style="display:none;" id="myDiv"></div>
  

Upvotes: 0

AxGryndr
AxGryndr

Reputation: 2344

Why not force a manual event when the button is clicked like so -

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

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

Upvotes: 4

Shah Nawaz
Shah Nawaz

Reputation: 396

You need to simply use keyup function:

$( "#myText").keyup(function(){
   alert($(this).val());
});

Upvotes: 0

Kenneth
Kenneth

Reputation: 28737

You'd need to connect both handlers. To reuse the handler you can extract it to a named function:

function showChanged(){
    alert('Changed!')
}

$("#myBtn").on('click', showChanged);
$("#myText").on('change', showChanged);

Upvotes: 0

VisioN
VisioN

Reputation: 145388

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/

Upvotes: 19

Related Questions