1

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.

4
  • Why you need nested form ? I didn't get the question. sorry Commented Aug 7, 2016 at 8:56
  • Um...The question is that I want to create a Post and many fruit. But the number of fruit is dynamic. And I want there is only one input field Commented Aug 7, 2016 at 9:28
  • ok. you can add multiple input fields dynamically. like, when user clicks add more product button Commented Aug 7, 2016 at 10:10
  • should I show it in JsFiddle ? Commented Aug 7, 2016 at 10:11

1 Answer 1

2

$(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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now I know how to figure it out!

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.