Osman
Osman

Reputation: 165

How to detect value changes of an input jQuery?

I am currently using this function to detect for any changes made to an input box in jQuery.

$(document).on("input change paste keyup", "input, textarea, select", function(e) {
    //do something
});

The problem is that when you change the value of an input through code such as this $("input").val(currentColorChosen);, the function does not run.

How do I solve this so that the function can detect all changes made to an input, including value changes made through jQuery.

Upvotes: 1

Views: 698

Answers (3)

Training at Manorama
Training at Manorama

Reputation: 167

I had just posted answer here

You can try using interval or timeout like this

var searchValue = $('#myTextbox').val();

function checkSearchChanged() {
    var currentValue = $('#myTextbox').val();
    if ((currentValue) && currentValue != searchValue && currentValue != '') {
        searchValue = $('#myTextbox').val();
       console.log(searchValue)
    }
    setTimeout(checkSearchChanged, 0.1);
}

$(function () {
    setTimeout(checkSearchChanged, 0.1);
});

checkout working plunker here

Upvotes: 1

slon
slon

Reputation: 1030

Add the one more line after your code:

$("input").val(currentColorChosen);
$("input").bind("change");

Upvotes: 0

Ioan-Radu Tanasescu
Ioan-Radu Tanasescu

Reputation: 566

$("input").change(function(){console.log("there was a change")}) and I think you can pass the value into it as well, it's a shortcut for .on( "change", handler )

More info: https://api.jquery.com/change/

Upvotes: 2

Related Questions