0

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> 
2
  • Are you actually using a input type="text" or a textarea? You are mixing up their syntaxes here. Commented Jun 7, 2010 at 11:22
  • In case you weren't yet aware of it, input type=text has an attribute maxlength with which you can define the highest amount of characters that can be entered into that field without javascript hacks. Commented Jun 7, 2010 at 11:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah. It is working fine now. Thanks alot. Could you share the concept behind it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.