I am validating text input on a html form, and would like to focus and select the text if it is invalid.
If my validation function looks like (just an example):
jQuery.fn.DateHelper = function(text){
return this.each(function(){
//Make sure we're dealing with text-based form fields
if(this.type != 'text')
return;
// call the processNumber function when the onBlur event is fired and there is a value in the field.
$(this).blur(function() {
if (this.value != '')
processNUmber(this);
});
function processNumber( txtField ) {
if (!isNan(txtField )) {
alert("not a number");
this.focus(); // this does not work.
// how to select text?
}
}
};
In your function you pass the
txtFieldparameter, use it instead ofthiswithin theprocessNumberfunction:Also you are declaring the
processNumberfunction inside the.each()loop in thejQuery.fn.DateHelperfunction which doesn’t have to be the case, you can declare that function outside the.each()and it will be accessible to any element on which this plugin is run.UPDATE
Your code functions however there are several syntactical errors:
Here is a demo: http://jsfiddle.net/uQ45E/6/