2012-04-06 16 views
1

Ich möchte überprüfen, ob Eingabefelder das erforderliche Attribut haben. Wenn diese Felder einen leeren Wert haben und das Attribut auch erforderlich ist, fügen Sie nach jedem Feld einen Fehler div hinzu. Ich habe ein wenig ratlos, wenn es um die Verwendung des Wahl kommtJquery Selector

// initialize validator for a bunch of input fields 
var inputs = $("#Contact :input") 

// Check all required fields 
if (inputs.attr("required") && inputs.val() === "") { 
    var invalidFields = Select all fields that have the attribute required and an empty value, and assign them a class 
    alert("Required Fields not completed"); 
} 

GELÖST. Danke Leute!

Antwort

0

versucht so etwas wie dies sollte es Klasse auf alle Eingaben hinzufügen, die die Kriterien erfüllen

$("#Contact :input").each(function(){ 
     if ($(this).attr("required") && $(this).val() === "") 
     { 
     $(this).addClass("req"); 

     } 
     }); 
0

können Sie verwenden, um die filter Funktion mit einem Rückruf die ausgewählten Elemente fehlen erforderlich diejenigen zu verengen:

var inputs = $("#Contact :input"); 

var missing = inputs.filter(function() { 
    return this.getAttribute("required") && this.value === ""; 
}); 
+0

dank guys..got es arbeitet – user1265533

0

Try this: http://jsfiddle.net/aramk/mK8YL/

HTML:

<input id="some" class="required" name="some" type="text" value="" /> 
<input id="submit_btn" type="submit" value="Go!" /> 

JS:

$(document).ready(function() { 

    $('#submit_btn').click(function() { 
     // initialize validator for a bunch of input fields 
     var valid = true; 
     var inputs = $("input.required").each(function() { 
      var input = $(this); 
      // Check all required fields 
      if (input.val() === '') { 
       input.addClass('invalid'); 
       valid = false; // Avoid a submit 
       alert("Required Fields not completed"); 
      } else if (input.hasClass('invalid')) { 
       input.removeClass('invalid'); 
      } 
     }); 
     if (valid) { 
      // This will submit 
      alert('submit successful'); 
     } else { 
      return false; 
     } 
    }); 

} 
); 
​ 

CSS:

.required { 
    background: yellow; 
    color: black; 
} 

.invalid { 
    background: red; 
    color: white; 
}​ 

Stellen Sie sicher, diese Eingaben in ein Formular für die Vorlage hinzuzufügen.

+0

WOW..thanks man..exactly, was ich brauche. – user1265533

2

durch jedes Element Looping sollte es tun

$("#Contact :input [required]").each(function(){ 
if($(this).val()===""){ 
//the input doesn't have a value, but is required 
//code here 
} 
}); 
+0

danke Jungs..got es funktioniert – user1265533