1

I'm working with autocomplete plugin in jQuery and I want to append the selection of my results to a div element with additional elements: a hidden input and a text input.

This is my html code:

This is my function in jQuery:

$("#buscar").autocomplete({
    source: "procesos/buscarPersona.php",
    minLength: 2,
    select: function( event, ui ) {
        $("#acreditados")
            .append('<div class="col50"><p>'
            + '<input type="hidden" name="id" value="' + ui.item.id_persona + '"/>'
            + ui.item.value 
            + '</p></div>'
            + '<div class="col50 f-right"><p>Monto:' 
            + '<input type="text" /></p></div>');
        }
});

By now my code is working fine, however I find difficult to maintain the append function which shows the selection result and the additional inputs. Is there a way I can use load() function to make this more simple? The final output must append multiple selections and not just the last selection

1 Answer 1

1

Don't use load, load is Ajax, meaning communication with server, for every selection unless you need some validation or more complex logic, we should avoid network access.

If you use load, then for each selection you will communicate with your server and then it will pass you the html.

IMHO this solution looks ugly but is more efficient.

Edit:

Keep this div separately:

    <div class="dynamiccontentcont">
       <div class="col50">
          <p><input type="hidden" name="id" value=""/></p>
       </div>
      <div class="col50 f-right">
         <p>Monto:<input type="text" /></p>
     </div>
   </div>

On selection

  1. Clone this div by calling jQuery('.dynamiccontentcont').clone()
  2. Place the selected values (As you are currently doing in your code)
  3. Append the div in your code
Sign up to request clarification or add additional context in comments.

3 Comments

Do you another way to make this more elegant? I just realized I need to add a delete button to every selection and it will make more ugly my code
The second div has an adittional class "f-right" so clone won't work as expected.
Edited my answer, wrap all the content inside parent and clone parent

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.