Insert html button as last element of jquery ui autocomplete list

I am trying to insert an html button as the last element of a jquery ui autocomplete list. The button should open a pop-up window with the ability to add a new item to the autocomplete list. This is the code that inserts the button inside the autocomplete list:

data.push({label: '<input type="button" name="btn_name_field" id="btn_name_field" title="Create" class="button firstChild" value="Add new">'}); response(data); 

This is the function that opens the popup:

 $(document).on("click", "#btn_name_field", function () { open_popup("Street_Address", 400, 180, "", true, false, {"call_back_function":"set_return","form_name":"EditView"}, "single", true ); }); 

To be able to embed html inside as a β€œlabel”, I had to use this function:

 $[ "ui" ][ "autocomplete" ].prototype["_renderItem"] = function( ul, item) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( $( "<a></a>" ).html( item.label ) ) .appendTo( ul ); }; 

What happens: the button looks normal and does what it should (opens a popup window) However, after opening the popup window, all the code from the html input is inserted into the text box. This is a logical behavior as the code is inserted as a label, but does anyone know what would be the best way to insert the html button as the last autocomplete element?

Thank you in advance

+6
source share
1 answer

If you use jQueryUI> = 1.9, this seems to work well for a response callback. This callback is called immediately after filling the original array, but before the elements are displayed to the user. You can use this event to enter a new "button" object in your array of sentences.

This "button" object has a label property, which is the HTML button of the button you are about to add, as well as a button property that is set to true. You can use this property to undo the default action of the select event:

 $.ui.autocomplete.prototype._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append($("<a></a>").html(item.label)) .appendTo(ul); }; $("#auto").autocomplete({ source: /* source */ response: function (event, ui) { // Add the "button" object to the list of suggestions: ui.content.push({ label: "<input type='button' value='click me' class='mybutton' />", button: true }); }, select: function (event, ui) { // If this is the button, don't populate the <input> if (ui.item.button) { event.preventDefault(); } } }); 

In addition, I would recommend using a delegated event handler instead of writing event handling code inside the markup that you create for the button. One way to do this is to give your button a class (I used .mybutton in the example) and write a delegated event handler with on :

 $(document).on("click", ".mybutton", function () { alert('clicked!'); }); 

Here is a working example: http://jsfiddle.net/J5rVP/35/

+4
source

All Articles