DinhNgocHien DinhNgocHien - 7 months ago 17
Javascript Question

How to show and hide field immediately base on the text length? - JQuery

I have two input text like this:

input1
<input type='text' id='input1' name='input1'>
<br>
input2
<input type='text' id='input2' name='input2'>
<br>


Now I want to hide and show
input2
base on the event in
input1
if there is no text in
input1
then
input2
will be hidden and vice versa. I write JQuery code like this:

$(document).ready(function () {
var inputText = document.getElementById("input1");
var textLength = inputText.value.length;
if (textLength <= 0){
$('#input2').hide("fast");
}
else{
$('#input2').show("fast");
}
});


It works only after each time refresh. So how to catch the input event in
input1
and affect the change immediately to
input2
?

Answer

You can try this code:

$(document).ready(function () {
  var input1 = $('#input1');
  
  function toggleInput() {
      if(input1.val().length) {
        $('#input2').show("fast");
      } else {
        $('#input2').hide("fast");
      }
  }
  
  toggleInput();
  
  $('#input1').on('keyup', toggleInput);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
input1
<input type='text' id='input1' name='input1'>
<br>
input2
<input type='text' id='input2' name='input2'>
<br>

Comments