0

I'm appending a form after successful AJAX call. When i'm trying to put validations by using id of that form its not working. Below is the example of my code.

HTML

<div id="dynamic_form"></div>

JavaScript

tab +=  '<form id="edu_edit_datails" method="post" action="" name="edu_edit_datails" enctype="multipart/form-data">';
tab +=  '<div class="form-group">';
tab +=  '<label for="course">Course:</label>';
tab +=  '<input type="text" class="form-control" id="course" value="" placeholder="Enter your Course" name="course">';
tab +=  '</div>';
tab +=  '<button type="button" class="btn btn-primary " id="submit_edit_edu_dtls">Submit</button>';
tab +=  '</form>';
$('#dynamic_form').html(tab);

Validation on click

$(document).on('click', '#submit_edit_edu_dtls' , function(e){
  if($("#edu_edit_datails").valid() == false) {
    alert("fail");
    return false;
  } else {
    alert(success);
    return true; 
  }
});
$("#edu_edit_datails").validate({
  rules: {
    course: "required"
  }
})

Any help is greatly appreciated! Thanks in advance.

1
  • 2
    Set validation rules after adding them to DOM, i.e. $('#dynamic_form').html(tab);$("#edu_edit_datails").validate(....) Commented Oct 23, 2017 at 8:12

1 Answer 1

2

You just need to validate the form (.validate) before you use the .valid()

var tab="";
tab +=  '<form id="edu_edit_datails" method="post" action="" name="edu_edit_datails" enctype="multipart/form-data">';
tab +=  '<div class="form-group">';
tab +=  '<label for="course">Course:</label>';
tab +=  '<input type="text" class="form-control" id="course" value="" placeholder="Enter your Course" name="course">';
tab +=  '</div>';
tab +=  '<button type="button" class="btn btn-primary " id="submit_edit_edu_dtls">Submit</button>';
tab +=  '</form>';
$('#dynamic_form').html(tab);
$("#edu_edit_datails").validate({
    rules: {
        course: "required"
    }
})
$(document).on('click', '#submit_edit_edu_dtls' , function(e){
    if($("#edu_edit_datails").valid() == false){
         alert("fail");
         return false;
    }else{
        alert("success");
        return true; 
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<diV id="dynamic_form"></div>

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

Comments

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.