I have a Ruby on Rails 4.0 application and I am wondering is it possible to pass a hidden param with JS to a form on form submit in Rails?
Asked
Active
Viewed 1,144 times
1
-
1Do you have any context? – Richard Peck May 21 '14 at 08:42
-
I have some data which is changed during my clicks in the application. This JS library has e method that returns the data. So, the data is changed dynamically and I do not want to add/remove hidden param after some event. That's why I am wondering is it possible to call this JS method before submit, it should return the final content and then I can set it to hidden param. – user1107922 May 21 '14 at 08:50
-
1You'll be able to do use the `.on("submit")` event in JS – Richard Peck May 21 '14 at 08:53
2 Answers
0
The way I would do this is to actually apply it in the controller (not JS):
#app/controllers/your_controller.rb
def create
@model = Model.new(controller_params)
@model.save
end
private
def controller_params
params.require(:controller).permit(:params).merge(param: "value")
end
Update
In light of your comment, you'd be able to use the .on("submit")
function in JS like this:
#app/assets/javascripts/application.js
$(document).on("submit", "#form", function(){
// append your params in here
});
As for adding the params, you could benefit from this: Adding POST parameters before submit
$('#commentForm').submit(function(){ //listen for submit event
$.each(params, function(i,param){
$('<input />').attr('type', 'hidden')
.attr('name', param.name)
.attr('value', param.value)
.appendTo('#commentForm');
});
return true;
});

Community
- 1
- 1

Richard Peck
- 76,116
- 9
- 93
- 147
0
Why not just add a hidden field in your form that has a default value? With simple_form and haml it will look like this:
= f.input :field, as: :hidden, default: :value

Justin Ho Tuan Duong
- 576
- 2
- 7