Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if input text has value, add class to label, remove it if no value

Tags:

jquery

I'm sure there are many similar questions here but still i can't find an answer to this. What i want is to add a class to the label on document ready if the input[type="text"] has a value and remove that class if the user will delete that input value ( better said, remove the label class if the input has no value on blur ).

Code so far:

    <div class="input-wrap">            
                <input type="text" name="textdemo" id="textdemo" size="20" value="" class="textdemo" />
            <label class="demo-label" for="textdemo">{L_USERNAME}</label>
    </div>


<script type="text/javascript">
jQuery(document).ready(function(){
    $('.input-wrap .textdemo').val() ) {
          $('label.demo-label').addClass('input-has-value');
    }

});
</script>
like image 826
COS Avatar asked Jan 04 '23 10:01

COS


1 Answers

This should do the trick:

function checkForInput(element) {
  // element is passed to the function ^
  
  const $label = $(element).siblings('label');

  if ($(element).val().length > 0) {
    $label.addClass('input-has-value');
  } else {
    $label.removeClass('input-has-value');
  }
}

// The lines below are executed on page load
$('input.textdemo').each(function() {
  checkForInput(this);
});

// The lines below (inside) are executed on change & keyup
$('input.textdemo').on('change keyup', function() {
  checkForInput(this);  
});
label.input-has-value {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-wrap">
  <input type="text" name="textdemo" id="textdemo" size="20" value="" class="textdemo" />
  <label class="demo-label" for="textdemo">{L_USERNAME}</label>
</div>
like image 176
dschu Avatar answered Jan 13 '23 14:01

dschu