Search code examples
htmlformsinputradio-button

Multiple values in radio input within form with vanilla HTML


I am aiming to create a form to handle disabled JavaScript experience for a small component on my website. Currently I have the following form:

<form method="GET" action="https://mywebsite.com/somedirectory/">

    <input type="radio" id="uid1" name="someParam" value="fruity" />
    <label for="uid1">Fruit</label>

    <input type="radio" id="uid2" name="someParam" value="veggie" />
    <label for="uid2">Vegetable</label>

    ...other radio options

    <input type="submit" value="Submit" />
</form>

Clicking on either of the radio options and then on the submit button will result in:

option 1: https://mywebsite.com/somedirectory/?someParam=fruity
option 2: https://mywebsite.com/somedirectory/?someParam=veggie

How can I add another value for each of the radio options? Say I would like to pass someOtherParam which is unique for each option and I would like to get this as output for my options:

option 1: https://mywebsite.com/somedirectory/?someParam=fruity&someOtherParam=apple
option 2: https://mywebsite.com/somedirectory/?someParam=veggie&someOtherParam=pepper

What I have tried is:

<input type="radio" id="uid1" name="someParam" value="fruity&someOtherParam=apple" />
<input type="radio" id="uid2" name="someParam" value="veggie&someOtherParam=pepper" />

However, the & symbol is converted to %26 inside the link and feels too hacky. Is there a better way to achieve this? Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?

P.S. I am aiming for pure HTML experience with no Javascript involved. Is that possible?


Solution

  • I'm pretty sure this is not posible in modern browsers without the use of JS. Maybe on old browsers you could do some tricks with CSS and display:none because it used to not send fields with display:none, but nowdays that is not an option.

    If you can allow Javascript, you can add a data attribute to each radio option and use it to populate an extra hidden input on change.

    document.querySelectorAll('input[type=radio][name="someParam"]')
      .forEach(radio => radio.addEventListener('change', (event) =>
        document.getElementById('someOtherParam').value = event.target.dataset.extraValue
      ));
    <form method="GET" action="https://mywebsite.com/somedirectory/">
      <input type="radio" id="uid1" name="someParam" value="fruity" data-extra-value="apple" />
      <label for="uid1">Fruit</label>
    
      <input type="radio" id="uid2" name="someParam" value="veggie" data-extra-value="pepper" />
      <label for="uid2">Vegetable</label>
    
      <input type="hidden" id="someOtherParam" name="someOtherParam">
    
      <input type="submit" value="Submit" />
    </form>