-3

I have one div in which their are 3 input fields of type text , I want to show alert on button click if any of the 3 input fields contain value.

<div id="userdiv">
<input type="text" name="username" />
<input type="text" name="company" />
<input type="text" name="area" /><br />
<button id="btn1">Search</button>
</div>

How can I check if any of the field contains value using jquery ?

4
  • Please take a little while to try coming up with an answer on your own! If you've already tried and can't figure it out, edit your question to include your attempt(s), and we can gladly help you out. Jul 31, 2018 at 14:12
  • you can google any number of examples of using JS / jQuery to validate data. Did you do any research? This isn't a free do-my-thinking service. We'll help you if you have an actual problem with some actual code.
    – ADyson
    Jul 31, 2018 at 14:17
  • 1
    If you spent a time searching this, you would have found your answer much faster than typing the question of your post,
    – Ray A
    Jul 31, 2018 at 14:19
  • 1
    Possible duplicate of jQuery check if any text input has value Jul 31, 2018 at 14:26

2 Answers 2

3

You can use a for loop to loop over all the input fields and get then check the value for each input field to check non-empty.

$('#btn1').click(function(){
  var input = $('#userdiv input[type="text"]');
  var found = false;
  for(var i=0; i<input.length; i++){
    if($(input[i]).val().trim() !== ''){
      found = true;
      alert('Non empty');
      break;
    }
  }
  if(!found){
    alert('all fields are empty');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="userdiv">
  <input type="text" name="username" />
  <input type="text" name="company" />
  <input type="text" name="area" /><br />
  <button id="btn1">Search</button>
</div>

1
  • So much code for a simple if ($('#userdiv input[type="text"]').filter(function() { return $(this).val().trim(); }).length > 0) alert("nope");
    – fdomn-m
    Jul 31, 2018 at 15:26
0

Something like this might work:

$('#btn1').on('click', function() {
    var myCondition = false;
    $('#userdiv').find('input').each(function() {
        if (!myCondition && $(this).val().includes('my_search_string')) myCondition = true;
    });

    if (myCondition) console.log('Found it!');
});

We can iterate through each <input> to check if any of them contain a specific string. If you want to only see if they contain something, then we can replace $(this).val().includes('my_search_string') with $(this).val().length since that will return FALSE unless the length is > 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.