0

So I have a form in Rails, very basic. But I decided to add some features. Little bit of context.
You choose either you're a man or a woman, and then the form generate some field. I had a field that was already existing in the V1, but when I generate it with javascript, it's not saved in DB. I don't really understand why. Here are some code.

Controller

def create
  @pokemon = Pokemon.new(params[:pokefuck])

  respond_to do |format|
    if @pokemon.save
      format.html { redirect_to '/pokemons', notice: 'pokemon was successfully created.' }
      format.json { render json: @pokemon, status: :created, location: @pokemon }
    else
      format.html { render action: "new" }
      format.json { render json: @pokemon.errors, status: :unprocessable_entity }
    end
  end
end

View

Original field that works

<%= f.select "size", options_for_select(size, @pokemon.size) %>

size is a hash

Created one, that does not work

var s = document.createElement("select");
s.name = "po";
s.id = "pokemon_size";
sex.appendChild(s);
for(i in size) {
  document.formName.po.options[i] = new Option(size[i], size[i]);
}

I supposed it was because the name of my new element wasn't pokemon[size], but when I used this, the line document.formName.pokemon[size].options[i] didn't work anymore.

So I'm kinda struggling to see how I can make this works. Thanks!

2
  • It might be because your new fields are created on the fly and hence not part of the original DOM. Commented Apr 12, 2013 at 9:55
  • So that would mean I have to create two different forms ? Meh. Commented Apr 12, 2013 at 10:58

2 Answers 2

1

Assuming from your controller code that your form fields are namespaced into "pokefuck", then you'll need to make the name of your select "pokefuck[size]", and then reference that name in the form's elements collection:

var s = document.createElement("select");
s.name = "pokefuck[size]";
s.id = "pokemon_size";
sex.appendChild(s);
for(i in size) {
  document.formName.elements['pokefuck[size]'].options[i] = new Option(size[i], size[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The name of the field needs to put it into the params hash for you your pokefuck.

pokefuck[size] should be the name of the form element. Append the form element to the form element you're submitting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.