jQuery event on value change of input hidden

后端 未结 4 699
遇见更好的自我
遇见更好的自我 2021-02-05 17:40

I have this input hidden:


I want to alert \"hey\

4条回答
  •  太阳男子
    2021-02-05 18:11

    The change event is fired after the blur event on an input, in other words when the input loses focus. The MDN documentation describes this:

    When the element loses focus after its value was changed, but not commited (e.g. after editing the value of or ).

    Since the input is of type hidden there will never be any user interaction with the input meaning it will not change unless the client side script provided by your site changes it, which will not trigger the change event.

    Here are two options:

    Call change() explicitly

    Whenever you modify the value of the hidden input call .change() to trigger the event.

    $(document).ready(function(){
        var $hello= $('[id$=myValue]');
    
        $hello.on("change", function(){
            alert('hey');
        });
    
        $hello.val("Something");
        $hello.change();
    });
    

    Just call the code without the handler

    Instead of using the event handler just execute the code you would have within the source.

    $(document).ready(function(){
        var $hello= $('[id$=myValue]');
        $hello.val("Something");
        alert('hey');
    });
    

    Another thing I would like to mention is the selector can be scoped a little better.

        var $hello= $('input[id$=myValue]');
    

    And if your using a new version of jQuery prefer on instead of bind as shown in the above example.

提交回复
热议问题