2

I have a simple question about Jquery and checkboxes. I have never worked with JQuery before but basically I have a checkbox and it will be set to "checked" by default when the user enters the page. I want jquery to detect that it is checked which will then trigger a separate function.

I've only been able to get this to work when the user click on the check box but I don't want it to do that. All this will be done without the user touching anything.

Here is the function that I have which doesn't work :

if ($('#discount:checked').val!== null) { changeprice(); };

Thank you in advance!

Beth
  • 21
  • 1
  • So you know how to trap the event? You just want to know how to tell if it is already checked? If so, kill the last semicolon. The rest should work fine. – clifgriffin Nov 17 '10 at 20:06

6 Answers6

2
$(document).ready(function(){
   if ($('#discount:checked').length > 0) { changeprice(); }
});
Adam
  • 43,763
  • 16
  • 104
  • 144
  • ..just of note: `if ($('#discount:checked').length) {...}` is the functionally the same as `if ($('#discount:checked').length > 0) {...}` Because -1 and 0 evaluate as false and any integer > 0 evaluates as true. – John Hartsock Nov 17 '10 at 20:17
  • @John Good point. However, I think that using conditions that do not evaluate to booleans is less readable. – Adam Nov 17 '10 at 20:21
  • @Adam...perhaps but after using this method and getting use to it, it becomes a matter of preference. – John Hartsock Nov 17 '10 at 20:23
1

You would likely want to save your code until the DOM instantiates. Fortunately, jQuery provides a great way to do just that:

$(document).ready(function () {
    if ($('#discount:checked').val !== null)
    {
        changeprice();
    }
});

The $(document).ready idiom is the standard way to make something happen as soon as possible after page load in jQuery.

Andrew
  • 14,325
  • 4
  • 43
  • 64
0

I think this is what you want:

if ($('#discount:checked').length == 1) { changeprice(); };
scunliffe
  • 62,582
  • 25
  • 126
  • 161
0
if ($('#discount').attr('checked')) changeprice();
Eduardo
  • 7,631
  • 2
  • 30
  • 31
0

Probably you can put the checkbox, checking code in document ready method,

$(document).ready(
  function(){
     if($("#discount").is(':checked')) { changeprice();}
   }
);

Regards, Jatan

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
jatanp
  • 3,982
  • 4
  • 40
  • 46
0

The jQuery val() method needs to be called like this:

if ($('#discount:checked').val() !== "") { changeprice(); }; 

On top of that, you should be using the $(document).ready() function to execute commands on page load.

Finally, it would be easier this way using the checked selector.

$(document).ready(function () {
  if ($('#discount:checked').length) {  // if the discount checkbox is checked
    changeprice(); 
  }
});
John Hartsock
  • 85,422
  • 23
  • 131
  • 146