The HTML on the page has 20 fields each named and given ID\'s in increasing order from 1 to 20.
If the variable id
is set to
(Try to use .blur()
instead of .focusout()
. But that probably won't help)
Try to remove the alert()
for a while - it sometimes can make problems with focus...
jsFiddle Example
This is my code, I'll explain what I changed:
$('input[id^="input"]').focusout(function(){
var selected = parseInt($(this).val(), 10);
if (selected <= 10) {
$("#input-"+selected).focus();
}
else {
alert('Invalid Argument! 1-10 only!');
$(this).focus();
}
});
focus()
instead of select()
which won't work.id
with select
which caused you to always try and select $("#input-IDOFSELECTIONINPUT")
instead of $("#input-IDOFWANTEDINPUT")
$("#"+id).select();
) in the undesired condition (input > 10
), which practically never gave it a chance.replace
$("#"+id).select();
by
$("#"+id).focus();
or even by
$(this).focus();
Try replacing:
$("#"+id).select();
With:
$(this).focus();
In this case, $("#"+id)
and $(this)
are the same element, and I'm assuming you want to focus
the element when there is an error.
Aside: I don't believe that id
or name
values can legally start with a number, you may want to prefix them with something like option1
, option2
, etc. It might work, but it might also cause issues later that are difficult to debug. Best to err on the side of caution and best practices.
What are valid values for the id attribute in HTML?
Edit: After failing to get focus()
to work, I tried with setTimeout
and was able to make it happen. I'm not sure why, or if this is really necessary, but it seems to work.
$(":input").focusout(function(){
var $this = $(this),
input = $this.val();
if (input > 10){
alert('You must enter a number between 0 and 10');
setTimeout(function(){
$this.focus();
}, 1);
}
});
I'd love to hear if there is a better way to do this or an explanation. I suspect that the blur and focus events are not fired in an order that makes the previous method possible?
Demo: http://jsfiddle.net/zRWV4/1/
As mentioned in the comments, you should eventually make sure the value is an integer with parseInt
or similar (you seem to already be aware of this).
You should parse the text inside the input to compare it with a number. var input = parseInt($(this).val());
'
$(":input").blur(function(){
var input = parseInt($(this).val());
var id = $(this).attr('id');
if(input > 10){
alert('You must enter a number between 0 and 10 '+id);
$("#"+id).select();
}
});