Search code examples
javascriptformsradio-button

Radio input and submit pass value


Im trying to make a radio button form where the chosen option, "123, 456" value is passed to the "data-offer-id" part of my submit button. I think this needs to be javascript but I don't know how to do this. Please help if you can!. Thanks in advance

<form>
  <input type="radio" name="data-offer-id" value="123"> 123<br>
  <input type="radio" name="data-offer-id" value="456"> 456<br>
 </form> 


<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id="***Need Value to dynamically populate here****"
                   data-completed-callback="cleengCallbackHandler(result)">    
<span style="color: #ffffff">$9.95 / Month
</span></button>

Solution

  • This would be handled when the radio button is clicked so that by the time the submit button is pressed, the value is already there.

    // Get reference to the submit button
    var sub = document.querySelector("button.btn-success");
    
    // Get a reference to both radio buttons as an array
    var radBtns = Array.prototype.slice.call(document.querySelectorAll("input[name='data-offer-id']"));
    
    
    // Loop over the buttons
    radBtns.forEach(function(btn){
      // Set each button to have a click event handler
      btn.addEventListener("click", function(){
        // Set the radio button's value as the id of the submit button
        sub.setAttribute("data-offer-id", btn.value);
        
        // Just for testing:
        console.clear();
        console.log(sub);
      });
    });
    <form>
      <input type="radio" name="data-offer-id" value="123"> 123<br>
      <input type="radio" name="data-offer-id" value="456"> 456<br>
     </form> 
    
    
    <button class="btn btn-success btn-large"
                        data-dismiss="learnmodal"
                        data-cleeng-trigger
                        data-action="checkout"
                        data-locale="en_US"
                        data-display-type="overlay"
                        data-offer-id=""
                       data-completed-callback="cleengCallbackHandler(result)">    
    <span style="color: #ffffff">$9.95 / Month
    </span></button>