2

I'm using the jQuery UI autocomplete widget on a text input. This text input is used to add a product to the database.

Here's my code:

HTML:

<div class="form-group">
    <input type="text" class="form-control" placeholder="Termék kiválasztásához kezdjen el gépelni..." id="search">
    <div id="autocomplete"></div>
</div>

JS:

$('#search').on('keypress', function () {
    $(this).autocomplete({
        appendTo: "#autocomplete",
        autoFocus: true,
        minLength: 0,
        source: "array - ommited for clarity"
    });
});

I would like to add a button which adds another input field, so the user can add another product to the database.

My problem would be, that if I duplicate the HTML I'm using, I'll have multiple elements with the same ID. Of course, the logical move would be to replace ID's with classes, but then again, if I'm correct the class selector for jQuery selects the first matched element, so the keypress event would fire on the original input.

How can I add another text input without duplicating my javascript code?

PeterInvincible
  • 2,230
  • 5
  • 34
  • 62
  • First of all, why are you initializing autocomplete inside `keypress` handler..?! Are you sure you want to re-initialize it every time you press a key..? *"if I'm correct the class selector for jQuery selects the first matched element, so the keypress event would fire on the original input."* - You're wrong. BTW you could've tested and confirmed it yourself... Try it and let us know if you get stuck with implementing it... – T J Nov 24 '14 at 15:53

1 Answers1

1

You can use class instead of the Id selector.

Please check this link : how-can-i-add-jquery-ui-autocomplete-to-a-dynamically-created-element

and this jsfiddle

<form id="myForm" name="myForm" method="post">
<input id="addButton" name="addButton" type="button" value="Add an input" />

$(function() {
var options = {
    source: [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
        ],
    minLength: 2
};

$("input.searchInput").live("keydown.autocomplete", function() {
    $(this).autocomplete(options);
});

var addInput = function() {
    var inputHTML = " <input name='search' value='' class='searchInput' maxlength='20' />";
    $(inputHTML).appendTo("form#myForm");
    $("input.searchInput:last").focus();
};

if (!$("form#myForm").find("input.searchInput").length) {
    addInput();
}

$("input#addButton").click(addInput);
});
Community
  • 1
  • 1
Anshuman Jasrotia
  • 3,135
  • 8
  • 48
  • 81