psharma
psharma

Reputation: 1289

Rails form getting submitted very oddly

I have the blelow form select

<%= f.select(:title, options_for_select([['Pick a reason',{:value => 0}],['Title 2', {:value => 1}], ['Title 3', {:value => 3}])) %>

So when somebody picks one of the three options from the dropdown, using jquery i am rendering one of the three in the text box.

<%= f.text_area :text , :rows => 10, :class=>"selectInput", :id=>"0", :style=>"display:none;", :value=>" text for pick reason"%>

<%= f.text_area :text , :rows => 10, :class=>"selectInput", :id=>"1", :style=>"display:none;", :value=>" text for title 1"%>

<%= f.text_area :text , :rows => 10, :class=>"selectInput", :id=>"2", :style=>"display:none;", :value=>" text for title 2"%>

But what happens is no matter what option is being selected, the last text_area entry gets saved in the db. In this case its

<%= f.text_area :text , :rows => 10, :class=>"selectInput", :id=>"2", :style=>"display:none;", :value=>" text for title 2"%>

How do i avoid that ? And make sure what is shown in the screen is what gets saved to the db.

Also here is my jquery

<script>
$(document).ready(function(){
    $('#bashing_title').change(function(){
        $(".selectInput").hide();
        $("#"+this.selectedIndex).show();
    });
});

</script>

Upvotes: 0

Views: 61

Answers (2)

PinnyM
PinnyM

Reputation: 35531

Although you are hiding several of the textarea's visually, this doesn't prevent them all from being submitted - and the last value to be serialized will be used by Rails.

Instead, you should have a single textbox, and modify the content depending on the selected option:

<% text_values = {"text0" => "text for pick reason", 
                  "text1" => "text for title1", 
                  "text2" => "text for title2" } %>
<%= f.text_area :text , :rows => 10, :class=>"selectInput", 
                :style=>"display:none;", :value => "", 
                :data => text_values %>

<script>
   $(function(){
     $('#bashing_title').change(function(){
       var textArea = $(".selectInput");
       textArea.show().val(textArea.data('text' + this.selectedIndex));
     });
   });
</script>

Upvotes: 1

kiddorails
kiddorails

Reputation: 13014

Why don't you use placeholder in textarea instead of value?

<%= f.text_area :text , :rows => 10, :class=>"selectInput", :id=>"2", :style=>"display:none;", :placeholder=>" text for title 2"%>

If the problem still pertains, it may be because those fields still exist in your DOM. Try modifying your jQuery code to remove() those fields which are not to be shown instead of hide()

Upvotes: 0

Related Questions