muqeem khan
muqeem khan

Reputation: 29

Conditional function based on either a checkbox is checked or not

$('#fastbill').click(function(){
    if ($('#changevaluebill').attr('checked','true')){
        $('#changevaluebill').attr("value","Recharge Now");
    }
    else {
        $('#changevaluebill').attr("value","Proceed");
    }
});

The checkbox condition is not working.

Upvotes: 1

Views: 1015

Answers (3)

laaposto
laaposto

Reputation: 12213

There are many ways to check if either a checkbox is checked

You can use is(':checked')

Try:

$('#fastbill').click(function(){
  if($('#changevaluebill').is(':checked')){
     $('#changevaluebill').val("Recharge Now");
  } else {
     $('#changevaluebill').val("Proceed");
  }
});

Other ways could be:

$('#changevaluebill').prop('checked') // Boolean
$('#changevaluebill:checked').length // Integer >0
$('#changevaluebill:checked').size() // .size() can be used instead of .length
$('#changevaluebill').get(0).checked // Boolean true
$('#changevaluebill')[0].checked // Boolean true (same as above)

Reference

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

As others has said, you need to can use .is() and :checked.

But you should use .val() to set the value of an input field

$('#fastbill').click(function () {
    $('#changevaluebill').val(function () {
        return this.checked ? 'Recharge Now' : 'Proceed'
    });
});

Upvotes: 1

David
David

Reputation: 218877

This isn't doing what you think:

$('#changevaluebill').attr('checked','true')

That doesn't determine if the value it 'true', it sets the value to 'true'. You can use the .is() function to conditionally check an aspect of the element. Something like this:

$('#changevaluebill').is(':checked')

Upvotes: 1

Related Questions