Reputation: 16239
I'm working on mvc4 project.
I want to set an validation alert message if my dynamically created textbox having null
value
for that i tried like following
function ValidateForm() {
debugger;
$("#MYFORM tr td").find("input:text").each(function (index) {
debugger;
if ($(this).attr("value") == undefined && $(this).attr("value") == "") {
alert("values are null..")
return false;
}
});
}
Please let me know the syntax for jquery to check the null value.
My problem is I have more than one TEXTBOX's in my FORM
Upvotes: 1
Views: 1099
Reputation: 3610
Use val()
function ValidateForm() {
var flag=0;
debugger;
$("#MYFORM tr td").find("input:text").each(function (index) {
debugger;
if ($(this).val() == undefined && $(this).val() == "" && $(this).val()==null) {//use val() here
alert("values are null..");
flag=1;
//$(this).css("border","1px solid red"); all input which are null will be have red border
}
});
if(flag==1){
return false;
}
else{
return true;
}
}
Upvotes: 2
Reputation: 1544
Your if
condition will never be true. Change it from:
if ($(this).attr("value") == undefined && $(this).attr("value") == "")
To:
if ($(this).attr("value") == undefined || $(this).attr("value") == "")
OR:
if ($(this).val() == undefined || $(this).val() == "")
Upvotes: 1
Reputation: 5992
working jsfiddle: http://jsfiddle.net/patelmilanb1/9NMmx/2/
$(document).ready(function () {
$('#MYFORM tr td').html("<input type='text' />");
});
$(document).on("blur", "#MYFORM input[type=text]", function () {
ValidateForm($(this));
});
function ValidateForm(element) {
if ($(element).val().length < 1) {
alert("values are null..")
}
}
you need to bind event on document level for dynamically created HTML elements.
Upvotes: 1
Reputation: 169
This is not related to jQuery.
In Javascript, one concept is undefined (value does not exist), other null and other empty string ''.
I suggest first checking for undefined and null, and then check for empty string Also I suggest cache the return value.
var val = $(this).val();
if(val == null || val.length == 0)
alert('values are null ...');
val == null is evaluated to true whether val is undefined or null.
Upvotes: 0
Reputation: 2286
You can use any of the following methods to check if the value is empty:
if(!$(this).val())
if($(this).val().length == 0)
Upvotes: 2