0

I have more that one text boxes with same name and class. I use jQuery validate to validate it as required. Issue here is when I submit the form without entering values for fields other than 1st check box, error messages are showing next to first textbox. For example if I submit form without entering values for 2nd textbox, it will show error message near to first text box. I think it is because of using same name/class for validation.

I have tried using class and name. No change. My sample code is given below. Any thoughts?

HTML part

<input type="text" class="unit_price" name="add_purch_unit[]">
<input type="text" class="unit_price" name="add_purch_unit[]">

jQuery Part

$(".unit_price").rules("add", { 
        required:true
    });
4
  • it is because of the same name... Commented Nov 11, 2014 at 6:04
  • But I use class here to validate Commented Nov 11, 2014 at 6:05
  • 2
    that is to add the rule... but internally the validator framework used element name Commented Nov 11, 2014 at 6:06
  • So, any idea to avoid that? Commented Nov 11, 2014 at 6:06

1 Answer 1

3
$(".unit_price").rules("add", { 
    required:true
});

Two problems with your code.

  1. You cannot attach a jQuery Validate method to a jQuery selector that targets more than one element. The solution for this part is to wrap the method within a jQuery .each().

    $(".unit_price").each(function() {
        $(this).rules("add", { 
            required:true
        });
    });
    
  2. However, you still cannot duplicate the name attribute. Even though we solved the problem from #1 above to assign the rule to every element with class="unit_price", the plugin uses the name attribute to keep track of all input elements. The solution is that you must also assign a unique name to each element... there is no workaround for this requirement.

    <input type="text" class="unit_price" name="add_purch_unit[1]">
    <input type="text" class="unit_price" name="add_purch_unit[2]">
    
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly what I was writing in my post, so I will just support this one and you should go with it too.
Thanks @Sparky .each also does same thing. I have tested that too. Anyway I have to use different names.
@Corner, no, .each() works fine only as long as you have unique name attributes. In other words, I did not provide you with two different solutions. No matter how you assign the rules, you must have unique name attributes.

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.