Pergunta

I have a jsfiddle, but I cannot make the javascript run correctly. The fiddle is at http://jsfiddle.net/davidm1181/suW6f/.

The javascript code that is stopping it is the following:

if ($(this).checked()) {
    $('.r1').val('true');
}

The problem is, that I have the same code running on my production web server and it works fine, and on my web server if I change checked() to just checked the code will still run, but it will always return true. Can somebody please help me understand this? Thank you.

Foi útil?

Solução

Explanation of your results:

There is no .checked() function for a jquery object. Therefore, when you call $(this).checked(), it results in the following error being thrown:

TypeError: Object [object Object] has no method 'checked'.

Also, there is no checked property for a jquery object. Therefore, the value of $(this).checked is undefined, which is considered falsy. (You say it always returns true, but I think that is a mistake.)

Correct way to check if a checkbox is checked:

You can use any one of the following:

if (this.checked) {
if ($(this).is(':checked')) {
if ($(this).prop('checked')) {

Which one you use is a matter of style.

Outras dicas

JSFIDDLE DEMO

Use

if(this.checked) or if($(this).is(':checked'))

instead of

if ($(this).checked()) {

Code:

$(':checkbox').change(function () {
    $('.r1').val(this.checked);
    $('.r2').val(this.checked);
});

There is nothing called .checked() in jquery or javascript

you can use

  1. .checked - use with this only
  2. .is(":checked") - use with $(this)
  3. .prop("checked") - use with $(this)

I have generated a fiddle here

When I have to validate if a checkbox is checked I use is(':checked'):

if ($(this).is(':checked')) {
    $('.r1').val('true');
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top