-11

How do you select a radio button using external link such as /page.html#item1 or /page.html?item1 so that when the page loads it's already selected

<input type="radio" name="price" id="item-1">
<input type="radio" name="price" id="item-2">
<input type="radio" name="price" id="item-3">

Any method will do, javascript or jquery

mr.data1
  • 721
  • 3
  • 10
  • 24
  • 3
    Firstly your `input` elements *need* to have a `value` attribute. Secondly, this is quite easy if you take the time to research. Break it down in to steps. [How do I get hash from URL?](https://stackoverflow.com/questions/298503/how-can-you-check-for-a-hash-in-a-url-using-javascript) [How can I get querystring values from URL?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) [How can I set selected radio?](https://stackoverflow.com/questions/4618733/set-selected-radio-from-radio-group-with-a-value) – Rory McCrossan Aug 18 '17 at 15:42
  • Value isn't important to explain what I'm looking for or for the function to work. Javascript isn't a language I know. I was hoping someone can show a working example. – mr.data1 Aug 18 '17 at 15:56
  • 1
    There is a difference between "I am having an issue with a specific problem." and "Can someone do it for me?". The first is what we are looking for from S.O. questions. – Taplar Aug 18 '17 at 16:04
  • This forum is full help with "how to" examples. Thanks for the vote down and a self-righteous attitude. Someone else got the credit. – mr.data1 Aug 18 '17 at 17:32

1 Answers1

1

Simple way to check radio button on window load.

Consider your url to be of form - scheme://example.com/myproject/abc.php?id=2

After running below code snippet you will encounter an error so try it on your site it requires url inorder to work.

$(window).on('load', function() {
  let prepend = 'item-';
  let elem = 'input[type=radio]';
  let url = window.location.href;
  let keyVal = '1';

  if (url.indexOf('?') !== -1)
    keyVal = url.split('?')[1].split('=')[1];

  let id = prepend + keyVal;

  $(elem).each(function(i) {
    if ($(this).prop('id') === id)
      $(this).prop('checked', true);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="price" id="item-1">
<input type="radio" name="price" id="item-2">
<input type="radio" name="price" id="item-3">
<input type="radio" name="price" id="item-4">
<input type="radio" name="price" id="item-5">

Hope, this works for you..!! :) :)

Chaitanya Ghule
  • 451
  • 1
  • 5
  • 11