rj487
rj487

Reputation: 4634

How rails do nested form in one form?

The scenario is that, I want to design a Post form which is used to record what fruit I eat in one meal, include picture, content, many kind of fruit. The model relationship is that,

Post has_many fruits
Fruit belong_to post

I usee Jquery-ui to make autocomplete in order to help user type their fruit. After they type there fruit tag, it will create a tag under the input field. Like this

enter image description here

However how to I create this in form? I thought about dynamic nested form, but I don't want there're a lots of form, I wish there would be only one input and do the same thing with dynamic nested form.

Here is the github, please let me know if I need to provide more information.

Upvotes: 1

Views: 407

Answers (1)

jaysingkar
jaysingkar

Reputation: 4435

$(document).on('click','#add_fruit',function(e){
  e.preventDefault();
  addFruitTag();
});

function addFruitTag(){
  var content = $('#content').val().trim();
  var fruit = $('#fruit').val().trim();
  if(content.length <1 || fruit.length < 1){
    alert("Please fill content and fruit");
  }else{
      $('#fruit_tags').append(
        $('<input>')
        .attr('type','checkbox')
        .attr('name','fruits[]')
        .attr('value',$('#fruit').val())
        .prop('checked','true')
      )
      .append(
        $('<label>')
        .text($('#fruit').val())    
      )
      .append($('<br>'));
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="#" method="GET">
  Content : <input type="text" id="content" name="content"><br/>
  Fruit : <input type="text" id="fruit">
  <button id="add_fruit">Add Fruit</button><br/>
  <div id="fruit_tags">
  </div>
  <input type="submit" value="Create Post">  
</form>

Note: I don't have much idea about auto complete plugin, so I have created the function addFruitTag(), call it where you are calling your function of adding hash tags of fruits.

And when you will submit the form to the server, you can retrieve the added fruits by accessing the fruits[] variable , which will be an array containing the selected fruits tags.

Upvotes: 2

Related Questions