Reputation: 5083
I need to validate bunch of text boxes which has dynamic ID. The elements are available on document ready, not dynamically inserted.
<input type="text" class="y"/>
<input type="text" class="y"/>
<input type="text" class="y"/>
<input type="text" class="y"/>
<input type="text" class="y"/>
The rule is that one of the first two field is required. I'm lost how to validate without knowing ID of the element.
EDIT: Input elements are generated by loop so I cant add class required for first two. I'm looking for a solution using jquery Validation plugin http://docs.jquery.com/Plugins/Validation
Upvotes: 4
Views: 548
Reputation: 1788
try This :
You can do it using :lt();
like this:
$("form input:lt(2)");
This selects all elements that match at less-than the passed index, the first and second elements are index 0 and 1, and will match this selector :)
Upvotes: 1
Reputation: 171689
Following uses filter to create collection of the 2 inputs that value is not empty.. Testing the length provides a validity test
var valid=$('input').slice(0,2).filter(function(){
return $(this).val() !='';
}).length
if(valid){
/* can submit*/
}
Solution for validation plugin:
$('input:lt(2)').addClass('required');
NOTE: adjust selector to fit form better so it doesn't find every input in page, or inputs in form that are not part of the collection you want to validate. you could wrap these inputs in a fieldset and give fieldset an ID
Upvotes: 2
Reputation: 82241
try this
$(document).ready(function() {
if($('input:text:eq(0)').val()=="" && $('input:text:eq(1)').val()==""){
//show error
}
});
Upvotes: 2
Reputation: 13071
I think that what you want is this:
function isValid(){
var cont=0;
$('input:text').each(function(i, obj) {
if(i<2 && obj.value){
cont++;
}
});
return cont==2;
}
Upvotes: 1
Reputation: 7954
$(document).ready(function() {
if($('input:text:lt(2)').val()=="" ){
//error
}
});
Upvotes: 1