0

I'm trying to pre-select a radio button based on a button click further up the page. The below code does work but it only seems to correctly select the radio option once.

jQuery(document).ready(function(){
  jQuery(".select-one").on('click', function(){
    jQuery("input[type='radio'][id='choice_25_25_0']").attr("checked", true);
});
   jQuery(".select-two").on('click', function(){
    jQuery("input[type='radio'][id='choice_25_25_1']").attr("checked", true);
});
   jQuery(".select-three").on('click', function(){
    jQuery("input[type='radio'][id='choice_25_25_2']").attr("checked", true);
});
});

Is there anything I can add to this code to enable it to run each time the button is clicked? Any help much appreciated.

JFiddle Example

Adam
  • 303
  • 4
  • 16
  • 1
    Post a [mcve] please – j08691 Sep 23 '21 at 15:22
  • 1
    Thanks for the [mcve] - if you look at the source of your page after clicking all the "buttons" (links), all of them have an *attribute* of `checked="checked"`. You need to use `.prop("checked", true);` to set the checked property, then it will work fine. – freedomn-m Sep 23 '21 at 16:01
  • I have edited my original post with a example of what is happening – Adam Sep 23 '21 at 16:02
  • 1
    You need to use `.prop()` instead of `.attr()` – j08691 Sep 23 '21 at 16:02
  • 1
    That's perfect. Thank you both for your help. Much appreciated – Adam Sep 23 '21 at 16:03
  • 1
    Does this answer your question? [jQuery: prop vs attr... clarification](https://stackoverflow.com/questions/10978870/jquery-prop-vs-attr-clarification) – freedomn-m Sep 23 '21 at 16:04
  • 1
    Or this: [prop() vs attr()](https://stackoverflow.com/questions/5874652/prop-vs-attr) – freedomn-m Sep 23 '21 at 16:04
  • TBH it's still a bit confusing - some people suggest *always* using `.prop` (and have downvoted answers that correctly suggest using `.attr`). – freedomn-m Sep 23 '21 at 16:06

1 Answers1

1

change to .prop() instead of .attr()

jQuery(document).ready(function(){
  jQuery(".select-one").on('click', function(){
    jQuery("input[type='radio'][id='choice_25_25_0']").prop("checked", true);
});
   jQuery(".select-two").on('click', function(){
    jQuery("input[type='radio'][id='choice_25_25_1']").prop("checked", true);
});
   jQuery(".select-three").on('click', function(){
    jQuery("input[type='radio'][id='choice_25_25_2']").prop("checked", true);
});
});
shazim ali
  • 360
  • 4
  • 18