Terry
Terry

Reputation: 1457

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

Upvotes: 0

Views: 397

Answers (1)

beeglebug
beeglebug

Reputation: 3542

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).

Upvotes: 1

Related Questions