Benno
Benno

Reputation: 149

Change default radio button using jQuery

I have a wordpress site with a plugin that gives me 2 radio buttons. These are Yes and No. Because Yes has a higher value than No the plugin chooses No as default. For visitors to my website, Yes would be the most common answer. That's why I'm looking for some code that chooses the other radio button after the page is loaded. After googling, copying and pasting I came up with this:

<script type='text/javascript'>
            $(document).ready(function(){
            var $radios = $('input:radio[name=vraag]');
                $radios.filter('[value=Yes]').attr('checked', true);
            });
        </script>

I've put this in my wordpress template but it's not doing anything. I don't know anything about jquery or javascript, I only know a bit of basic HTML so I desperately need some guidance. Any one who can point me in the right direction please??

Upvotes: 0

Views: 3646

Answers (3)

Santhosh Rajkumar
Santhosh Rajkumar

Reputation: 121

Use below code for default select option in document.ready function

$("input:radio[value='PM']").attr("checked","checked");

Upvotes: 1

Benno
Benno

Reputation: 149

Let me answer my own question. Unfortunally the solution of FERMIS did not work for me. With a lot more searching i found something that not only works, bit uses the value of the radio button so should even work with more than 2 radio buttons. This is the code

$(document).ready(function(){ $('input[value="Yes"]').attr('checked', 'checked');

Simple and short, but effective :)

Upvotes: 0

Fermis
Fermis

Reputation: 181

in jQuery you could do this.

HTML

<input type='radio' name='type' class='radio-buttons' id='yes'>Yes
<input type='radio' name='type' class='radio-buttons' id='no'>No

Javascript

$(function(){ //shorthand for $(document).ready(function(){
   $('#no').removeAttr("checked"); // selects id no and unchecks it
   $('#yes').attr('checked', true);  // selects id yes and checks it
});

EDIT:

Javascript

$(function(){
   // This will switch all radio buttons on the page, assuming you only have those 2.
   $radio_buttons = $('input:radio');
   $radio_buttons.each(function(){
      if ($(this).is(':checked')){
         $(this).prop('checked', false);
      }
      else{
         $(this).prop('checked', true);
      }
   }
});

Upvotes: 0

Related Questions