I am new to php and jquery. I want validation for input type text.
<input type="text" size="5" name="add_qnty[]" value="">
I have tried the server side scripting but no use. So please help me so that my submit will redirect only if all textboxes will fill with data.
Try this: Add 'class=required' to all the required fields in the form and send these fields as an array to the below function like:
checkFrmFill( $( "#formid").find(".required"));
and the function will be:
function checkFrmFill(inputs) {
var returnVal = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "text" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].tagName == "SELECT" && ( inputs[i].value == "select" || inputs[i].value == 0 ) || inputs[i].value == "" || inputs[i].value == null) {
returnVal = false;
} else if (inputs[i].type == "password" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].type == "textarea" && inputs[i].value == "") {
returnVal = false;
}
}
return returnVal;
}
This will return false for those fields that are blank.
For every text input add required attribute at the end of the tag.
<input type="text" size="5" name="add_qnty[]" value="" required>
<input type="text" size="5" name="add_qnty[]" value="" required>
HTML
...........................
form id ='frm'
submit button id ='submit_frm'
SCRIPT
.............................
$(function(){
$('#submit_frm').click(function(){
$('#frm').find('em.err').remove();
$('#frm').find('input[type=text]').each(function(){
if($(this).val()==''){
$(this).parent().append('<em class="err">This field is required</em>');
}
});
if($('#frm').find('em.err').length > 0 ){
return false;
}else{
return true;
}
});
});
Try this: Working Example JSFIDDLE
$("form").on("submit",function(){
var len = $("input[name='add_qnty[]']").filter(function() {
return !this.value;
}).addClass("has-error").length;
alert(len);
if(len == 0){
return true; // Submit form
} else {
return false; // Validation failed
}
})