开发者

Using document.activeElement with an onChange event to validate a textbox only after textbox change is completed

I have already implemented a version of the code below on my development system.

function validateTextBox(textBoxId) {

  var textBox = document.getElementById(textBoxId);

  if(document.activeElement.id != textBox.id) {

    do validation

  }

}

The HTML is similar to:

<input type="text" id="ValidateMe" onChange="validateTextBox('ValidateMe');"/>

The idea is that validation takes place only after the user has completed editing the textbox and that, unlike an onBlur event, validation only fires when the value开发者_Python百科 of the textbox has actually changed.

It seems to work I'm just leery of using it without some review and feedback. I haven't seen any similar code examples. So please give me your thoughts on the implementation and any alternate ideas you may have.

Thanks


This is a fine solution. Do keep in mind that the onchange event will typically only fire when the focus changes (ie. onblur)

If you want to do validation while the user is typing you can use onkeydown/onkeyup/onkeypress but that's quite a ways harder.

Additionally you can use this so you don't have to assign an id to each field and remember to pass it to the validate function:

function validate(input_element) {
    alert(input_element.value)
}
<input type="text" name="name" onchange="validate(this);"/>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜