Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the jquery change event not trigger though the value of input changed indeedly? [duplicate]

JSFIDDLE

Html Code:

<body>
    <input value="123">
    <button>button</button>
</body>

Js Code(using JQuery 1.2.0):

$(function(){
    $("button").click(function(){
        $("input").val("balabala...");
    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});

Question:
At the beginning, the value of the input is "123".

When I change the text through editing by hands and click other places not the input field, the change event of the input will trigger.

However, when I click the button, which will also change the value of the input, the change event of the input will not work.

Thanks for any help.

like image 900
Shaowei Ling Avatar asked Oct 20 '25 14:10

Shaowei Ling


2 Answers

The change event is not triggered when changing the value programatically with code, you have to trigger it yourself

$(function(){
    $("button").click(function(){
        $("input").val("balabala...").trigger('change');
    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});

FIDDLE

like image 72
adeneo Avatar answered Oct 23 '25 03:10

adeneo


JSFiddle

You need to append .change() onto the click function:

$(function(){
    $("button").click(function(){
        $("input").val("balabala...").change();

    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});
like image 36
Albzi Avatar answered Oct 23 '25 04:10

Albzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!