Been doin' a bit of googling with no success. I'm trying to fetch the value of the current value in another fo开发者_StackOverflow中文版rm's text field and pass it along to a controller. Any ideas on the best way to go about this?
It sounds like you're trying to get data from 2 different forms on a single HTML page. If I understand you correctly, this isn't possible on the backend. When a browser submits a form, it only submits the fields for that single form. If you want to share a value between 2 different forms you will need to use JavaScript to either…
- Use a single form and dynamically add/remove fields and set the action URL
- Copy the fields from the non-submitted form to the submitted form when the user clicks submit (before the browser actually sends the request).
- Grab the data from the fields and merge it together, then send a request via AJAX and redirect the browser to the result page (or do something else with the result).
Make sense?
EDIT:
Regarding your comment that option 2 would work for you, that's pretty straightforward:
$('#form-1').submit(function(){
$('#form-2 [name]:not([type="submit"])').appendTo(this);
});
I don't have many details, but one way you could do this regardless of the form is to pull the data from the text field via jQuery and then make an AJAX call to the controller:
So in your application.js you could do:
$.ajax("/controller/action", {
cache: false,
data: {
_method: "POST",
textfield-data-param: (textfield-data)
},
success: function (jqXHR, status) {
//Do something on a success
},
complete: function (jqXHR, status) {
//do something on complete
},
type: "POST"
});
In your controller you could do something like:
def action
@data = params[textfield-data-param]
respond_to do |format|
if @data.save
format.js { head :ok }
else
format.js { head :unprocessable_entity } # Maybe find a better status code to use.
end
end
end
Sorry, its a very broad answer, but hopefully it will give you a lead.
精彩评论