Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the any of my textbox is empty or not in javascript [duplicate]

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!

like image 331
ray Avatar asked Sep 15 '12 12:09

ray


People also ask

How do you check if a text box is blank?

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.

How check multiple textbox is empty in jQuery?

click(function(e) { var isValid = true; $('input[type="text"]'). each(function() { if ($. trim($(this). val()) == '') { isValid = false; $(this).


2 Answers

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)')
}
like image 102
undefined Avatar answered Sep 26 '22 13:09

undefined


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');
    });
});
like image 33
Adil Avatar answered Sep 23 '22 13:09

Adil