5

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');
  }
});

5 Answers 5

6

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is a much better way to do it then what I answered with
3

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');
});

Comments

3

try checking the value on a doc ready:

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

EDIT: just as an update to this answer, a nicer approach might be to use toggle class, set up in doc ready then trigger the event to run on page load.

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');
});

Comments

2

Well then why dont just check the field after the page is loaded?

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.