0

I have two inputs with classes (q1, q2) and a div with class (output). I would like to be able to hide the div when one or all of the inputs have "any value". I'm new to javascript.

$(document).ready(function() {
  $('.q1, .q2').keyup(function() {
    if ($(this).val().length == 0) {
      $('.output').show();
    } else {
      $('.output').hide();
    }
  }).keyup();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="output">Test</div>
<input type="text" value="" class="q1">
<input type="text" value="" class="q2">

2 Answers 2

1

You need to check both input values to achieve your goal like this:

$(document).ready(function() {
  $('.q1, .q2').keyup(function() {
    var q1 = $('.q1').val();
    var q2 = $('.q2').val();

    if (q1.length || q2.length) {
        $('.output').hide();
    } else {
        $('.output').show();
    }
  }).keyup();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="output">Test</div>
<input type="text" value="" class="q1">
<input type="text" value="" class="q2">

Sign up to request clarification or add additional context in comments.

Comments

0

Haseeb has given a great answer.

Just wanted to mention as you're new to JQuery / Javascript it's often worth checking the existence of classes before using them, as it prevents changes to the HTML further down the line causing unexpected issues.

$(document).ready(function() {
     // Check if the classes exist here
     if ($(".q1")[0] && $(".q2")[0] ) {
          $('.q1, .q2').keyup(function() {
            var q1 = $('.q1').val();
            var q2 = $('.q2').val();
        
            if (q1.length || q2.length) {
                $('.output').hide();
            } else {
                $('.output').show();
            }
          }).keyup();
        }
    });

3 Comments

You don't really need to check their existence in this case, if q1 and q2 class are not present in the DOM, this function will simply not fire, without causing any issue.
if($(".q1")[0]) isn't very clear. Better stick with tried and tested if ($(".q1,.q2").length). But, as above, not needed as $(".q1,.q2").keyup will only be applied to q1/q2 that already exist at the time, so no need to check - when adding events (but other times, this may be good practice)
Thank you @freedomn-m, that's helpful to know about .keyup()

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.