Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Check if input is empty not checking onload?

I am using this code to check if an inputbox is empty or not and it works fine but it only checks check a key is press not when the page loads.

It's does what it should but I also want it to check the status when the page loads.

Here is the current code:

$('#myID').on('keyup keydown keypress change paste', function() {
  if ($(this).val() == '') {
    $('#status').removeClass('required_ok').addClass('ok');
  } else {
    $('#status').addClass('required_ok').removeClass('not_ok');
  }
});
like image 522
Satch3000 Avatar asked Jan 13 '12 10:01

Satch3000


2 Answers

Try the following:

$(function() {
  var element = $('#myID');
  var toggleClasses = function() {
    if (element.val() == '') {
      $('#status').removeClass('required_ok').addClass('ok');
    } else {
      $('#status').addClass('required_ok').removeClass('not_ok');
    }
  };
  element.on('keyup keydown keypress change paste', function() {
    toggleClasses(); // Still toggles the classes on any of the above events
  });
  toggleClasses(); // and also on document ready
});
like image 58
Rich O'Kelly Avatar answered Sep 25 '22 19:09

Rich O'Kelly


The simplest way to do is trigger any of the keyup,keydown etc event on page load. It will then automatically call your specific handler

$(document).ready(function(){
  $("#myID").trigger('keyup');
});
like image 22
Anupam Avatar answered Sep 23 '22 19:09

Anupam