fourroses
fourroses

Reputation: 134

Let link deside what radio button is checked

I have 3 links on a page, when clicking on one of the links, the radio button on the other page needs to be checked.

Looks like this:

<a href="page.html?amount=1">Go 1</a>
<a href="page.html?amount=2">Go 2</a>
<a href="page.html?amount=3">Go 3</a>

I have some checkboxes on the page.html which needs to be checked.

<input type="radio" name="amount" value="1" />
<input type="radio" name="amount" value="2" />
<input type="radio" name="amount" value="3" />

When click on Go 2, checkbox 2 needs to be checked. Anyone knows what js needs to be written?

Upvotes: 1

Views: 1517

Answers (2)

Hanky Panky
Hanky Panky

Reputation: 46900

<input type="radio" name="amount" value="1" /> 1 <br>
<input type="radio" name="amount" value="2" /> 2 <br>
<input type="radio" name="amount" value="3" /> 3 <br>


<script>
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    }


var am=getQueryVariable("amount");
var allElems = document.getElementsByName('amount');
for (i = 0; i < allElems.length; i++) {
    if (allElems[i].type == 'radio' && allElems[i].value ==am ) {
        allElems[i].checked = true;
    }
}
</script>

Reference: getQueryVariable() function is taken from Here. Credit goes to @ Dorian Gray

Upvotes: 1

James
James

Reputation: 13501

You'll need to get the querystring using Javascript - plenty of information on how to do that, one example: How can I get query string values in JavaScript?

You'll then need to write some Javascript to select the radio button - again, a simple search is your friend: javascript check radio buttons automatically

Top tip: use the search engine :)

Upvotes: 0

Related Questions