Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am facing a problem with jQuery Validation to validate the ajax (dynamically) generated text fields...

Here is the snippet of the HTML code

         <form name="booking" id="booking" method="post" action="">
              <ul>
                <li>
                    <span>Mobile Number</span>
                </li>
                <li>
                <input  type="tel" name="mobile" id="mobile" class='form_mobile'/>
                </li>                    
                   <li>
                    <span>Number of male tickets</span>
                </li>
                <li>
                       <select name="male_qunatity" id="male_qunatity" >

                        </select>
                </li>
            </ul>
        </form>

Jquery validation script is here

     $(document).ready(function(){

Here is the ajax call starts

 $('#male_qunatity').change(function() {

        var male_tickets = $(this).val();      
        var mobile = $('#mobile').val();
        var path = '<?php echo site_url() ?>';
        ajaxurl = path + '/wp-admin/admin-ajax.php';
        var data = {
            action: 'get_quantity',
            qty: male_tickets,
            mobile: mobile
        };

          $.post(ajaxurl, data, function(response) {
            $('#m_attendees').html(response);
        });

     }); //END dropdown change event


       $("#booking").validate({
          });

      $('.form_mobile').each(function() {
      $(this).rules('add', {
        required:true,
        number:true,
      messages: {
        required:"Please enter a mobile number",
        number:"Only numbers allowed"
       }
     });
  });

  });//validation ends

Here is the ajax code to text-boxes based on the count selected

    $quantity=  $_REQUEST['qty'];
    $mobile=  $_REQUEST['mobile'];
    $pass = "<table>";
      for($i =0; $i<$quantity; $i++ ){
    $pass .= "<tr>
       <td>
      <input type='text'  id='mobile-".$i."' class='form_mobile' name='mmobile[]'>
      </td>
          </tr>";
       }
    $pass .= "</table>";
    echo $pass;

FYI: The form validation is working fine for the form fields, except the dynamically created fields..

How to solve this one?

Any suggestions would be greatly appreciated..

share|improve this question
1  
Your question is very unclear. However, if you're creating fields dynamically, then you would call .rules('add') AFTER the fields are dynamically created. –  Sparky Jun 19 at 15:54
    
@sparky As i am calling the change event and ajax before the .rules('add').. Updated my question. –  PHPCoder Jun 19 at 15:58
    
No, you're not really. When .rules('add') is called the dynamic fields don't yet exist. –  Sparky Jun 19 at 15:59
    
@Sparky I am wondered why the class name validation not working for the dynamic fields..Is there any mistakes in the code? –  PHPCoder Jun 19 at 16:00

2 Answers 2

up vote 1 down vote accepted

1) Since jQuery Validate depends on the name attribute, you'll need to alter your PHP to ensure that every name is unique. Note the index, $i, added to the name attribute...

"... <input type=text  id='mobile-".$i."' name='mmobile[".$i."]' class='form_mobile'> ..."

(you're also missing quotes around text; should be type='text')

2) When creating fields dynamically, you would call .rules('add') AFTER the fields are dynamically created. In your case, here...

$.post(ajaxurl, data, function(response) {
    $('#m_attendees').html(response);   // <- create the new fields
    $('.form_mobile').each(function() { // <- then dynamically add the rules
        $(this).rules('add', {
            required:true,
            number:true,
            messages: {
                required:"Please enter a mobile number",
                number:"Only numbers allowed"
            }
        });
    });
});

3) .validate() is the initialization method for the plugin on your form. Just call it once when the DOM loads. (.validate() does not get called repeatedly when the form is validated, because validation is automatic once the plugin is properly initialized.)

$(document).ready(function() {  // <- DOM is ready

    $("#booking").validate({    // <- initialize plugin on your form
        // your options         // <- plugin options
    });

});
share|improve this answer
    
so where can i call the "$("#booking").validate({ });" ??? If i add after $("#m_attendees").html(response) then it only validates after change event occurs.. –  PHPCoder Jun 19 at 16:14
    
@PHPCoder, There was nothing in my original answer saying to move .validate(). See the code I posted. You would call the .validate() method ONCE to initialize the plugin on your form. You'd do that within the DOM ready event handler. In other words, just leave it where you originally had it. –  Sparky Jun 19 at 16:27
1  
+1 Validation working now.. Thanks for your suggestions and quick response –  PHPCoder Jun 19 at 16:29
    
@PHPCoder, you're welcome. Also noticed you're missing the quotes around text in your HTML. input type='text' –  Sparky Jun 19 at 16:44
    
Thanks for pointing.. corrected that one in code..Thanks –  PHPCoder Jun 19 at 16:49

You have to execute the validation code after the ajax call.

Means you have to call your Jquery validation script after the ajax call means after this following line in ajax call

$('#m_attendees').html(response);
share|improve this answer
    
jQuery Validation does not get called more than once on DOM ready, and only to initialize the plugin on the form. The rules() method is the only thing that needs to be called immediately after the field is created. –  Sparky Jun 19 at 16:06
    
Then there is no way to validate the form loaded using ajax...??? –  itzmukeshy7 Jun 19 at 16:07
    
He's not loading the form with ajax, just some input fields. There is a difference between initializing the validation plugin and dynamically adding some rules. –  Sparky Jun 19 at 16:09
    
But when a field is added to DOM using ajax call means validation rules won't apply on that field because of the validation function is already called to validate those fields we have to call validation function again there is no other way to validate those fields...if you know any please share with me... thanks :) –  itzmukeshy7 Jun 19 at 16:14
    
Perhaps you are unaware that you cannot call the .validate() method more than once. All subsequent calls are always ignored, which means you cannot use .validate() to change any options or rules. This is why the plugin provides the .rules() method for dynamically changing rules after the plugin is first initialized with .validate(). –  Sparky Jun 19 at 16:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.