PDA

View Full Version : Trying to use dynamic variable...



parallon
Mar 15th, 2007, 08:39 PM
Hello all. Not sure if this is possible, but I have 14 text fields which I want to validate for numbers on OnBlur. Here is what I have so far...

Note: 'n' is the name of the text box I want to validate.

function chkNumber(n) {

var field = n
if (isNaN(document.frmAddMileage.(field).value)) { // If it is not a number...

document.frmAddMileage.(field).style.background = "#99ccff"; // ... change field to this color.
alert("Please enter a valid number for your odometer reading.");
frmAddMileage.(field).focus();
frmAddMileage.(field).select();
return
}
else document.frmAddMileage.(field).style.background = ""; // ... change field to this color.
}

Any suggestions would be greatly appreciated.

Parallon

glenngv
Mar 15th, 2007, 08:57 PM
function chkNumber(n) {
var frm = document.frmAddMileage;
if (isNaN(frm.elements[n].value)) { // If it is not a number...

frm.elements[n].style.background = "#99ccff"; // ... change field to this color.
alert("Please enter a valid number for your odometer reading.");
frm.elements[n].focus();
frm.elements[n].select();
return
}
else frm.elements[n].style.background = ""; // ... change field to this color.
}
That's square bracket notation. See my sig for more info on it.

glenngv
Mar 15th, 2007, 09:05 PM
You can pass the field object reference itself to the function instead of its name.


function chkNumber(field) {
if (isNaN(field.value)) { // If it is not a number...

field.style.background = "#99ccff"; // ... change field to this color.
alert("Please enter a valid number for your odometer reading.");
field.focus();
field.select();
return;
}
else field.style.background = ""; // ... change field to this color.
}
...
<input name="txt1" onblur="chkNumber(this)" />
<input name="txt2" onblur="chkNumber(this)" />
...

But take note that in some browsers, you may have an infinite alert because of blur and focus events. It's better you implement the validation on form onsubmit or use onblur but take off the alert and have a message displayed beside the field.

parallon
Mar 15th, 2007, 09:19 PM
Thank you so much... That worked perfectly! (I tried the second way)

Parallon