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">
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">
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();
}
});