0

Why is this code not working on jQuery 1.10.1?
Fiddle here -> http://jsfiddle.net/XgDwU/9/

<input type="radio" id="don" name="billing[use_for_shipping]" value="">Ship to this address</input>
<input type="radio" id="don1" name="billing[use_for_shipping]" value="">Ship to different address</input>
<br/><br/>
<b> <input type="checkbox" id="chkSelect" /> Check/Uncheck me </b>
<br/><br/>
<p></p> 

here's my function

$(document).ready(function() {
  $('#chkSelect').click(function(){

    var isChecked = $('#chkSelect').is(':checked');
      if(isChecked){
          $("input#don").attr('checked',true);
          $('p').html('Checkbox is checked: <b>True</b>');
      }else{
          $("input#don1").attr('checked',true);
          $('p').html('Checkbox is checked: <b>False</b>');
      }
  });
});
Jonas
  • 121,568
  • 97
  • 310
  • 388
user3364265
  • 35
  • 1
  • 8

2 Answers2

1

Problems:

  1. Use change event instead of click
  2. Use prop instead of attr
  3. I have use this.checked in place of $('#chkSelect').is(':checked')

Try

$(document).ready(function() {
    $('#chkSelect').change(function(){
      if(this.checked){
          $("input#don").prop('checked',true);
          $('p').html('Checkbox is checked: <b>True</b>');
      }else{
          $("input#don1").prop('checked',true);
          $('p').html('Checkbox is checked: <b>False</b>');
      }
    });
});

DEMO

You should read .prop() vs .attr() a very good explanation is provided

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

You are trying to add a check attribute to a radio button. If more than one radio button in a set has the checked attribute, the latter will be checked. That's what's happening, more than one radio is being checked.

Since it's a radio button, and the browser handles the switching, just trigger a click on the one that you want:

$('#chkSelect').click(function () {
    if (this.checked) {
        $("input#don").click();
        $('p').html('Checkbox is checked: <b>True</b>');
    } else {
        $("input#don1").click();
        $('p').html('Checkbox is checked: <b>False</b>');
    }
});

JSFiddle

George
  • 36,413
  • 9
  • 66
  • 103