Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if any text input has value

I want to ask if there's a better way in jQuery to select multiple text input then check if any of them has a value. Here's my code:

if ($("#reference").val() != "" || $("#pin").val() != "" || $("#fName").val() != "" || $("#mName").val() != "" || $("#datepicker").val() != "") { /*logic goes here */ } 
like image 824
dilm Avatar asked Mar 10 '14 07:03

dilm


People also ask

How can check input value or not in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.

How do you check all input field is not empty in jQuery?

Just use: $("input:empty"). length == 0; If it's zero, none are empty.


2 Answers

You could do like below:

if ($("#reference,#pin,#fName,#mName,#datepicker").filter(function() { return $(this).val(); }).length > 0) {   //.. } 

Using a common function like the following would make it reusable:

function hasValue(elem) {     return $(elem).filter(function() { return $(this).val(); }).length > 0; } 

And you could call it like this:

hasValue("#my-input-id"); 
like image 170
xdazz Avatar answered Sep 21 '22 00:09

xdazz


Try jQuery each()

 $('input[type=text]').each(function(){      var text_value=$(this).val();      if(text_value!='')        {         console.log('Value exist');         }     }) 
like image 43
Shijin TR Avatar answered Sep 20 '22 00:09

Shijin TR