Joel James
Joel James

Reputation: 1345

jQuery validate error message misplaced

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
    });

Upvotes: 0

Views: 390

Answers (1)

Sparky
Sparky

Reputation: 98738

$(".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]">
    

Upvotes: 3

Related Questions