2016-05-19 8 views
0

Ich habe diese Form:find() each() nicht etwas zu finden

<form method="post" action="#" data-action="ajax.php?method=create" class="form-horizontal" role="form"> 
    <div class="form-group"> 
     <label class="col-md-2 control-label">Name</label> 
     <div class="col-md-8"> 
      <input name="name" type="text" value="" class="form-control" required> 
     </div> 
    </div> 
    <div class="form-group"> 
     <label class="col-md-2 control-label">Location</label> 
     <div class="col-md-8"> 
      <input name="location" type="text" value="" class="form-control" required> 
     </div> 
    </div> 
</form> 

Ich möchte einige grundlegende Validierung dieser Form durchzuführen. Mein find(). Each() -Code funktioniert jedoch überhaupt nicht.

Hier ist der Code:

$(document).on('submit', '[data-action]', function (event) { 
    event.preventDefault(); 

    var form = $(this); 

    // ensure required fields are filled in 
    form.find('[required]').each(function() { 
     alert('required field found'); 
    }); 
}); 

ich keine Warnungen sogar deutlich bin immer wenn die Form 2 erforderlichen Eingaben hat.

Warum passiert das?

+0

Wo ist die Schaltfläche zum Senden in Ihrem HTML? –

+0

Hoppla, ich habe vergessen, es in der Frage hinzuzufügen. Aber ja, es gibt einen Absenden-Button im Formular. – kjdion84

Antwort

0

Chromes eingebauten Browser Validierung wurde mein Code von der Ausführung zu stoppen. Durch das Hinzufügen von novalidate zu meinem Formular wurde das Problem behoben.

0

Sie müssen Ihre Absenden-Schaltfläche innerhalb Ihrer Formular-Tags hinzufügen. Wenn das erledigt ist, funktioniert Ihre JQuery. Hier

ist ein Link zu einer Fiddle Demo

HTML

<form method="post" action="#" data-action="ajax.php?method=create" class="form-horizontal" role="form"> 
    <div class="form-group"> 
    <label class="col-md-2 control-label">Name</label> 
    <div class="col-md-8"> 
     <input name="name" type="text" value="" class="form-control" required> 
    </div> 
    </div> 
    <div class="form-group"> 
    <label class="col-md-2 control-label">Location</label> 
    <div class="col-md-8"> 
     <input name="location" type="text" value="" class="form-control" required> 
    </div> 
    </div> 
    <input type="submit" value="submit"> 
</form> 

JQUERY

$(document).on('submit', '[data-action]', function (event) { 
    event.preventDefault(); 
    var form = $(this); 
    console.log($(this)); 

    // ensure required fields are filled in 
    form.find('[required]').each(function() { 
    console.log('required field found'); 
    }); 
}); 
+0

Deine Geige funktioniert nicht. (getestet in Chrome) – kjdion84

+0

@ kjdion84 - Ja, es funktioniert. Sie müssen die Chrome-Entwicklertools (F12) öffnen und auf der Konsolenregisterkarte nachsehen, um die Ergebnisse zu sehen. Sie werden sehen, dass ich Ihre "Warnung" durch "console.log()" ersetzt habe, was eine weniger aufdringliche Art ist, mit dem Debugging umzugehen. –