Search code examples
javascripthtmlradio-buttonhidden-field

How do it have a radio button pass data hidden from url?


Here is the thing, I have to show a proof of concept, in which I:

  • Pass data from page to page using the url section and displaying the data passed in another page.

  • Pass data from page to page NOT using the url section and displaying the data passed in another page.

Meaning I want one of the radio button to behave as: input type="hidden", But I do not know how to do that, to clarify there is a code snipped below. Any help is appreciated. To clarify, it should not show the value of the radio button in the query string.

<form method="POST" action="Confirm.jsp">


  <p>
    Choose:
    <input type="radio" checked name="QuizType" value="Private">Private
    <input type="radio" name="QuizType" value="Public">Public
    <br>

    <input type="submit" name="submit" value="submit">
  </p>
</form>


Solution

  • Your form:

    <form id="frm1">
    <p>
      Choose:
      <input type="radio" checked name="QuizType" value="Private" id="radio">Private
    
      <input type="radio" name="QuizType" value="Public">Public
    
      <button onclick="myFunction()">Click</button>
    </p>
    </form>
    

    Then you can get the selected value with JavaScript:

    function myFunction() {
      var radios = document.getElementsByName('QuizType');
    
      for (var i = 0, length = radios.length; i < length; i++) {
         if (radios[i].checked) {
    
           // Store the value for the selected radio 
           // You can maybe redirected on another page and pass this variable
           $selectedRadio = radios[i].value
    
           alert($selectedRadio);
           break;
         }
       }
    }
    

    Check this Example.

    If you want to pass variables to the url then you should try:

    window.location.href+'/'+$selectedRadio;
    

    Resources: Get Radio Button Value with Javascript, Is there a way to pass javascript variables in url?, How to redirect to another webpage in JavaScript/jQuery?