简体   繁体   中英

Rails3.2 option chooser in form

I'm new to Rails and I have a big problem with an option chooser. The user can choose per checkbox, if he wants to use a selectbox or a text_field. The jquerycode does his job by showing or hiding the div. But when i submit the form, :task_name gets always the value of the task_new div but never the one of the task_use . What I'm doing wrong?

Is there a way for hiding/showing the div via rails function? Maybe i set up some tmp variables and give :task_name the value?! How can this be done?

Update: I tried the trick with the tmp_variables . The get an value but now I stuck, how to set the value of the tmp_variable to :task_name . <% :task_name = @tmp_variable%> doesn't work.

Here's the code (new.html.erb):

 Create new Task :
  <input type="checkbox" value="false" name="check" id="check" checked="false" />
  </div>

  <div class="task_use" id="task_use" style="display:block;">
    <%= f.fields_for :task do |t|%>  
    <%= t.select :task_name, Task.all.collect {|n|[n.task_name]}%>
    <%end%>
 </div>
  <div class="task_new" id="task_new" style="display:none;">
    <%= f.fields_for :task do |t|%>
    <%= t.label :task_name %><br />
    <%= t.text_field :task_name %>
    <%end%>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
  <% end %>

   <script>

   $(document).ready(function() {
   $("#check").change(function () {
   if ($('#check').checked == false) {

   } else {
   $('#task_new').toggle();
   $('#task_use').toggle();
   }
   });
   }); 
   </script>

For Rails it does not matter which div is shown or hidden. Both code fragments will be evaluated. The second fragment thus simply overwrites any values set for task_name.

You could use two seperate forms and toggle between those but i suppose you have more fields than those listed above which you do not want to toggle :)

Maybe you could try and replace the actual task_name DOM element (somwhat a "real" toggle) and at the same time copy the values as this guy did but it sounds quite complicated :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM