Reputation: 101
I am using the below validation for textbox which accepts only alphabets and maximum of 50 characters. I am passing the object directly in the parameter. The below case by giving the field name i.e "my_text" directly is working is working fine. But if i pass it in variable, that time it is not working(commented the if statement). Please help me. My requirement is each time when we enter the charater, the hardcode field name should not be used in the validation.
<html><head>
<script language=JavaScript>
function check_length(my_form,fieldName)
{
alert(fieldName);
// if (my_form.fieldName.value.length >= maxLen) {
if (my_form.my_text.value.length >= maxLen) {
var msg = "You have reached your maximum limit of characters allowed";
alert(msg);
my_form.my_text.value = my_form.my_text.value.substring(0, maxLen);
}
else{
var keyCode = window.event.keyCode;
if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123) && keyCode != 32)
{
window.event.returnValue = false;
alert("Enter only Alphabets");
}
my_form.text_num.value = maxLen - my_form.my_text.value.length;}
}
</script>
</head>
<body>
<form name=my_form method=post>
<input type="text" onKeyPress=check_length(this.form,this.name); name=my_text rows=4 cols=30>
<br>
<input size=1 value=50 name=text_num> Characters Left
</form>
</body>
</html>
Upvotes: 0
Views: 224
Reputation: 413702
Try this:
if (my_form[fieldName].value.length >= maxLength)
When referencing a property of an object, the forms
object.constantName
and
object['constantName']
are the same. Note that in the second one, I quoted the property name. When you use the square brackets instead of the "." to reference a property, Javascript evaluates the expression in square brackets. In your case, you always have a variable that must be evaluated, so you have to use the square brackets.
Upvotes: 3