Using Rails and Formtastic to make a dynamic form
I am trying to make a very simple dynamic form. I am using Rails 3.1 and formtastic. Basically, I want to change a couple of fields based on a radio button.
It would look something like.. What kind of a shape are you making? (Radio Button with a choice of square or rectangle) If square is selected one new field for size is displayed. If rectangle is selected two fields are displayed for size.
The table will actually have only one size column, so the model will munge the po开发者_Python百科tentially two fields into one before the ultimately hit the database (i think, still working on this issue as well)
Anyway, it is my understanding that I would need to use javascript in order to change the form. I am pretty javascript illiterate and really don't understand how to use it with formtastic. Any pointers would help.
Thanks!
Yes, you should use js to do that. If you're new to js don't hesitate and learn jQuery, it's becoming sort of js standard for rails now.
To do what you want you should display both size fields in your view and show/hide second field depending on radio values. It can be something like that:
$(function() {
var $radios = $("input[name=radioName]");
var $size2 = $("#size_field_2");
function toggleSizeField() {
$size2.toggle($radios.filter(":checked").val() == 0);
}
$radios.click(toggleSizeField);
toggleSizeField();
});
精彩评论