简体   繁体   中英

jquery validate multiple dynamically added fields

I am trying to validate multiple dynamically added fields on a form before submit using jquery but when one field is valid, the form is being submitted: http://jsfiddle.net/cvL0ymu7/ . How can I validate all fields before the submit.

<html>
    <body>
        <form action="#" method="post">
            <div id="fields"></div>
            <input type="submit" value="Submit" />
        </form>
        <button id="test">Add field</button>
    </body>
</html>

Le JavaScript

$(function() {
        $("#test").click(function(){
            var unique_id = new Date().getTime(); 
            $("#fields").append("<input class='myfield' type='text' name='myfield_" + unique_id + "'/><br />");
        });

      $( "form" ).submit(function( event ) {

      if ( $( ".myfield" ).val() !== "" ) {
        alert("form is valid");
        //$( "span" ).text( "Validated..." ).show();
        return;
      }

      //$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
      alert("form is invalid");
      event.preventDefault();
});

}); 

Please check this fiddle ....this what you want to do...

enter code here http://jsfiddle.net/cvL0ymu7/

Can you try MY CODE HERE

$( "form" ).submit(function( event ) {
      var vaild = true;
      $('.myfield').each(function(){
          if ($(this).val().trim() == '') {                 
              vaild = false;
              return;
          };
      });
      if (valid) {
          alert("form is valid");
      } else {
          alert("form is invalid");
          event.preventDefault();
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM