开发者

jQuery onchange event fires twice in IE8

开发者 https://www.devze.com 2023-03-27 04:25 出处:网络
I have the following code: <html> <head> <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js\" type=\"text/javascript\"></script>

I have the following code:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
</head>
<body>

    <script type="text/javascript">

        $(document).ready(function()
        {
            $('#test').bind("change", function()
            {
                alert(this.value);
                this.value = jQuery.trim(this.value);
            });
        });

    </script>

    <input type="text" id="test" />
    <br /开发者_JAVA技巧>
    <input type="radio" />
</body>
</html>

In IE8 if i enter any text to "test" input and press "Tab" I'll get alert message twice.

But if I comment line "this.value = jQuery.trim(this.value);" the message will be shown only once.

Why this happened? And how I can avoid twice "onchange" handler invoking?


The Issue has been reported in jQuery and it has been fixed with the latest code base. That was reported on jQuery 1.4 - 1.6.4.


When you set the value property of a form element to a different value, the change event fires.

So, in your code:

$('#test').change(function() {
    // This is executed whenever the `change` event fires
    // Setting a new value will trigger the `change` event again
    this.value = $.trim(this.value);
});

By the way, you probably want to use the input event instead of change. There’s a jQuery plugin for that: https://github.com/mathiasbynens/jquery.oninput.js

0

精彩评论

暂无评论...
验证码 换一张
取 消