2

I set up a JavaScript program using jQuery to change the user input values at various form field.

$(document).ready(function(){
    $("#billAmt").keyup(function(){
        var a = $("#billAmt").val();
        var b = a*3/100;
        var d = "<%= current_user.balance %>";
        var c = d - b;
        $("#cashBack").val(b);
        $("#total").val(c);
    });
});

This JavaScript code is inside the form_tag and I would like to pass #cashBack to hidden field.

I did like:

<%= hidden_field_tag :cashBack, nil, :id => "cashBack", :value => ''%>

When I submit the form, params[:cashBack] is empty. So, how do I pass the value and change every time I change the value.

3
  • can you show me what you get a,b,c in keyup event Commented Apr 29, 2016 at 1:48
  • I pass a value in text field with id billAmt. Lets say I enter 100 and user balance is 200 then a = 100, b=3, c = 197 Commented Apr 29, 2016 at 1:53
  • this value didi you got when you console.log() Commented Apr 29, 2016 at 2:17

1 Answer 1

5

In order to set hidden textfield, You must use pure javascript instead of JQuery.

$("#cashBack").get(0).value = b;                  
Sign up to request clarification or add additional context in comments.

1 Comment

This is the so far the best answer for how to pass variable from javascript to hidden_field/rails erb. Simple and it works like a charm. Thank you ;) Can you describe why we cannot use jQuery and what method get do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.