Ad

How To Have A Radio Checked On Page Load

I have a donation page using Liquid Shopify. I CANNOT change name="donation[amount_option]" (I do not have access to that file) so I need code that allows this to stay.

I want to have $250 automatically checked on load

My code

document.querySelector('input[name="donation[amount_option]"][value=250]').checked = true;
<div class="radio-inline donation-v2-amounts padbottommore">
  <span>
    <input id="donation_amount_25" type="radio" name="donation[amount_option]" class="donation_amount_option" value="25">
    <label for="donation_amount_25" class="radio">$25</label>
  </span>
  
  <span>
    <input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250">
    <label for="donation_amount_250" class="radio">$250</label>
  </span>
  
  <span>
    <input id="donation_amount_1000" type="radio" name="donation[amount_option]" class="donation_amount_option" value="1000">
    <label for="donation_amount_1000" class="radio">$1,000</label>
  </span>
</div>

Ad

Answer

If you need a pure js alternative (in addition to the answer above). You can select by value:

document.querySelector('input[value="250"]').checked = true;

EDIT:

In case it isn't clear, you can use any valid selector such as the id, i.e.:

document.querySelector('#donation_amount_25').checked = true;.

Ad
source: stackoverflow.com
Ad