开发者

Input change event on blur

I need to trigger an input change event, but only if the value changed. And I need this done from a keyboard event. Is there a way to invoke the browser's change mechanism which will either trigger the change event to fire, or will not depending on if the value was modified?

Example:

User clicks on an input field
User does not modify开发者_如何转开发 value of the field
user presses a key causing the input field to blue
onchange does not get triggered.

vs

User clicks on an input field
User modifies the value of the field
user presses a key causing the input field to blue
onchange gets triggered.    

Is this possible? Or I need to do the onfocus save value, onblur compare and possibly call onchange, but only if onchange was not already called because the user just navigated away by clicking vs say a keyboard trigger.


What key is it? If that key isn't a standard input key, set the onchange to check the field for the change of the field.

You also can bind an onkeypress do the document, and return:false; when the key that changes the input to blue is pressed.

A little more context could help.


If I get you right, you need two variables to remember previous and current states of the input, and a listener to handle interaction:

<html>
<head>
<script language="javascript">
var startFieldValue = "Some value, possibly value of input when it is loaded";
var endFieldValue = "";
var focusFlag = 0;
function interact(keyEvent) {
    if(focusFlag == 1)
        return true;
    var key = keyEvent.keyCode? keyEvent.keyCode : keyEvent.charCode
    if(String.fromCharCode(key) == "a") {
        if(startFieldValue != endFieldValue) {
            var elem = document.getElementById('input-to-be-changed');
            elem.style.backgroundColor = "blue";
            startFieldValue = endFieldValue;
        }
    }
}
</script>
</head>
<body onkeypress="interact(event);">
<input id="input-to-be-changed" onchange="endFieldValue = document.getElementById('input-to-be-changed').value;" onfocus="focusFlag = 1;" onblur="focusFlag = 0;">
</body>

Just read the comment on previous post, you should have global idea of what's going on, though. Changes are removing checking for focus, and placing listner (onkeypress) inside every input. The function interact should take 2 values - event and id of input to focus next. Also focusing new element should change startFieldValue. Sorry to not write code itself, but it's kinda late and I really need some sleep.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜