简体   繁体   中英

How can I keep the focus on an input field if the input is incorrect

Given the following code:

sPosSelect="#fpJpos input[name=posnum" + iiPos + "]";
if (fIn>fPosMaxWtUse[iiPos]) {
    alert(sprintf('%.0f is %.0f more than the position max of %.0f.',fIn,fIn-fPosMaxWtUse[iiPos],fPosMaxWtUse[iiPos]));
$(sPosSelect).val('');
$(sPosSelect).focus();
return;
}

It works in that I get the alert, and the field is blanked. However, the focus then moves on to the next field when what I want is for it to stay on the field just blanked so the user can try again.

All suggestions are welcome, including anything I'm doing that could be done in a better way.

Terry

I assume your code is within an event attached to the field in question, presumably on blur?

If this is the case, you should simply use return false at the end of the function. This will tell the browser to ignore it's default behaviour, which in this case would be moving to the next field.

What your code is doing at the moment is setting focus in the field, and then returning control to the browser, which assumes everything went okay, and happily moves on to the next field.

Also, if this code is within an event attached to the field, you should really be using $(this) in place of repeating the selector $(sPosSelect) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM