Radio button onclick change url and checked

In my checkout page i have a set of 2 radiobuttons with onClick. How to have them checked based on selected/current url?

 <div class="b2bc">
<p>CUSTOMER TYPE: </p>
<form action="">
  <input type="radio" name="customertype" value="private" onclick = "document.location.href='https://mywebsite.com/order'"><a> PRIVATE</a>
  <input type="radio" name="customertype" value="business" onclick = "document.location.href='https://mywebsite.com/business/order'"> <a>BUSINESS</a>
</form>
</div>

You would run a JS script that sets the checked property based on the URL.

Please can help me with this JS script?

In JavaScript, document.URL is what you see in the URL field of the browser.

Give the radio buttons an ID the same as the name.

Place the following just before the closing </body> tag.

<script>
    (function setRadio(){
        const thisURL = document.URL,
            rad = document.getElementById('customertype');
        switch(thisURL){
            case "https://www.mywebsite.com/order":
                rad[0].checked = true;
            break;
            default:
                rad[1].checked = true;
            break;
            }
        })();
</script>

Not tested, but let me know if you have any questions.

V/r,

^ _ ^

Otherwise the browser would have complained about invalid property access. document.getElementById() returns an Element instance, not a NodeList.

That’s right… it’s been a while. I assumed that since there were two elements with the same ID it would return an array. Dangit, jQuery, yer screwing up my method of thinking!!! :slight_smile:

I should have used document.formname.customertype[0] and document.formname.customertype[1].

V/r,

^ _ ^

1 Like

even jQuery only returns one of the elements …

Two radio buttons with the same ID, and you’re telling me that jQuery will return only one element if I use $('#customertype') as the selector?

V/r,

^ _ ^

According to jQuery, the selector returns a jQuery object which, I believe, is at least array-like, if not an array. So $('[name=customertype]').each() will iterate through an array (or array-like jQuery object) and conduct whatever instructions are within the () of each.

HTH,

^ _ ^

The jQuery object internally uses an array to store the elements (and applies every operation on that array). But even then jQuery only selects one of the multiple elements (since it internally uses getElementById() for that case).

If at all possible, serve one of them with a checked attribute from the backend depending on the request. Otherwise @WolfShade’s approach would do the trick (going with the name though – IDs must of course be unique). ;-)

Dw reminded me of that. :slight_smile: I changed it back to name and it works.

V/r,

^ _ ^

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.