JQuery Check if input is empty without checking onload?

I use this code to check if the input file is empty or not, and it works fine, but it only checks the validation key, which does not press when the page loads.

It 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');
  }
});
+5
source share
5 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
});
+6
source

try checking the value on the finished document:

$(function() {  
    if ($('#myID').val() == '') {
        $('#status').removeClass('required_ok').addClass('ok');
    } else {
        $('#status').addClass('required_ok').removeClass('not_ok');
    }
});

EDIT: As an update for this answer, a more convenient approach could be to use the toggle class, configure in the finished document, and then fire the event to load on the page.

function check() {
    var $status = $('#status');

    if ($(this).val()) {
        $status.toggleClass('required_ok').toggleClass('ok');
    } else {
        $status.toggleClass('required_ok').toggleClass('not_ok');
    }
}


$(function () {
    $('#myID').on('keyup keydown keypress change paste', check);
    $('#myID').trigger('change');
});
+3
source

- keyup, keydown .. .

$(document).ready(function(){
  $("#myID").trigger('keyup');
});
+3

, ?

$(document).ready(function(){
  if ($('#myID').val() == '') {
    $('#status').removeClass('required_ok').addClass('ok');
  } else {
    $('#status').addClass('required_ok').removeClass('not_ok');
  }
});
+2
$(document).ready(function(){
var checkVal = $("myID").val();
if(checkVal==''){
$('#status').removeClass('required_ok').addClass('ok');
}
else{
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
+2

All Articles