Possible Duplicate:
Check if inputs are empty using jQuery
I have form and textboxes, how will I determine if any of these textboxes is empty using javascript if else statement once a form button is clicked.
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
Thanks in advance!
IsNullOrEmpty() function has a boolean return type and returns true if the string is either null or empty and otherwise returns false . We can use the String. IsNullOrEmpty() function on the string inside the TextBox. Text property to check whether the text inside the text box is empty or not.
click(function(e) { var isValid = true; $('input[type="text"]'). each(function() { if ($. trim($(this). val()) == '') { isValid = false; $(this).
By using jQuery selectors for selecting the elements, you have a jQuery object and you should use val()
method for getting/setting value of input elements.
Also note that :text
selector is deprecated and it would be better to trim the text for removing whitespace characters. you can use $.trim
utility function.
function checking() {
var textBox = $.trim( $('input[type=text]').val() )
if (textBox == "") {
$("#error").show('slow');
}
}
If you want to use value
property you should first convert the jQuery object to a raw DOM object. You can use [index]
or get
method.
var textBox = $('input[type=text]')[0].value;
If you have multiple inputs you should loop through them.
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
})
alert(empty + ' empty input(s)')
}
You can not use value
with jquery object use val()
function, But this will check only the first textbox returned by the selector.
Live Demo
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
You can attach blur
event and do this validation on losing focus from each textbox.
Live Demo
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
Validation on submit button
click according to discussion with OP
Live Demo
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With