Satch3000
Satch3000

Reputation: 49404

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

Upvotes: 5

Views: 3674

Answers (5)

atmd
atmd

Reputation: 7490

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

Upvotes: 3

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

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

Upvotes: 6

arun
arun

Reputation: 21

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

Upvotes: 2

Anupam
Anupam

Reputation: 8016

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

Upvotes: 3

Hannes
Hannes

Reputation: 8237

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

Upvotes: 2

Related Questions