Cameron Bass Cameron Bass - 6 months ago 96
Javascript Question

Conditional Hidden Field Tag - Rails

Right now I'm hardcoding a an plan_id into a hidden field tag. This works great when a user selects the free plan that my app offers. But, when They select a paid plan that obviously has a different ID this messes everything thing up. My form uses JS to render a payment partial if the plan_id is a paid plan but skips the payment partial if its a free plan. So, How can I dynamically set the params based on if a user select a paid plan or free plan. Here is my code.

<%= hidden_field_tag :plan_id, 1 %>
<%= f.submit "Select", class: "button-big reverse-blue" %>

If the user selects this. The object is created and the everything is great. But this is only one option. The user can also select this.

<input type="radio" name="plan_id" id="plan_id_5" value="5" data-plan-form-next data-plan-name="Surveillance Van" data-plan-price="79" />
<span class="button-big reverse-blue">Select</span>

If the user selects this button the JS hides this page and unhides the payment form. When the user types in the payment information and submits the form everything works fine except now they have the
of 1, instead they should have the
of 5. Can I set the params of plan_id 1 in the submit button?

So, with all of this being said. How can I not hardcode the params to be a plan Id of one unless the pick the free plan? Hopefully this is clear enough let me know if you need to see more code or more explanation.


this is bit hacky but you can use jQuery to assign value to the hidden field based on which radio button is selected

assign an id to your hidden_field_tag

<%= hidden_field_tag :plan_id, '', id: 'plan_id_hidden'%>

then use jQuery or just plain javascript to set its value. with jQuery

  $( "[type=radio]" ).change(function() {
    if ($("#plan_id_1").is(':checked')) {
    } else if ($("#plan_id_2").is(':checked')) {
    } else {