I am using jquery and json to save data to the database. How can I apply validation on textboxes. if conditions fails i have applied return false; still json data saving code executes.
$('input[type=text]').each(function() {
// Ex: Person['FirstName'] = $('#FirstName').val();
//NewPerson[this.id] = this.value;
if ($(this).val() == '') {
alert('Please Enter ' + this.id);
return false;
}
});
var DTO = { 'NewPerson': NewPerson };
$.ajax({
type: "POST",
开发者_高级运维 contentType: "application/json; charset=utf-8",
data: "{'FirstName':'" + $("#FirstName").val() + "', "
+ "'LastName':'" + $("#LastName").val() + "',"
+ "'Zip':'" + $("#Zip").val() + "'}",
etc.
How to stop datasaving code to execute?
Your each() is closed before the row var DTO = { 'NewPerson': NewPerson};
I think you could refactor your script like this
var isValid = true;
$('input[type=text]').each(function() {
if ($(this).val() == '') {
isValid = false;
}
});
if(isValid){
var DTO = { 'NewPerson': NewPerson };
$.ajax( {type: "POST",
contentType: "application/json; charset=utf-8",
data: "{'FirstName':'" + $("#FirstName").val() + "', " + "'LastName':'" + $("#LastName").val() + "'," + "'Zip':'" + $("#Zip").val() + "'}"});
}
精彩评论