jQuery input event fired on placeholder in IE

拈花ヽ惹草 提交于 2020-01-24 04:26:07

问题


I have an input field with an input event bound to it (via jQuery). This event should be fired everytime the input value changes. I added a placeholder to tell the user what this input field is for.

If the user clicks on this input field the input event should NOT be fired (the value actually doesn't change; just the placeholder disappears). It works fine in Firefox or Chrome but not in IE.

How can I avoid this behavior?

For better understanding my problem on jsfiddler


回答1:


One way to guard against the problem is by storing the old value of your field and checking against it before performing the real function you want to perform in your input handler. This is how I fixed it in one of my applications.

For instance:

$(document).ready(function () {
    var $input = $("#input");
    var $msg = $("#msg");
    var old_value = $input.val();
    $input.on("input", function () {
        var new_value = $input.val();
        if (new_value !== old_value) {
            // The actual work we want to perform when the field *really* changes.
            $msg.text(new_value.length);
            old_value = new_value;
        }
    });
});

This prevents acting when the field is not changing.




回答2:


try adding this to the input event:

if($(this).val() == $(this).get(0).defaultValue) return;


来源:https://stackoverflow.com/questions/19289396/jquery-input-event-fired-on-placeholder-in-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!