Multiple jQuery autocomplete in one page - php

UPDATE
I checked the dropdown elements and it seems that the succeeding dropdown elements are not populated by the
.data( 'ui-autocomplete' )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append(
'<a class="select-group"><span class="mini-headtitle">' + item.institution_name +
'</span><br/><span class="mini-subtitle">' + item.municipality + '</span></a>' )
.appendTo( ul );
};
}
part. But the "missing" elements still has the items needed! How do I solve this?
PROBLEM
I have dynamically added textboxes which correspond to a jQuery Autocomplete script.
Whenever a new textbox is added to the DOM, it should also have the same autocomplete from the first.
Autocomplete works on all newly added DOM textboxes but only the first instance has its select box filled with options.
First textbox
Succeeding textboxes
My textboxes have the id InstitutionName[1] where the number grows as more elements are added.
I use the code below:
function ajax_connect_to_db()
{
$('input[id^="InstitutionName"]')
.autocomplete({
minLength: 0,
source: "new_account/get_institution_info_db",
dataType: "json",
focus: function( event, ui ) {
$( this ).val( ui.item.institution_name );
return false;
},
select: function( event, ui ) {
// get unique textbox number inside brackets
var str = $(this).attr('id');
var pos = str.indexOf("[") + 1;
var index = str.slice(pos, str.lastIndexOf("]"));
// fill in the respective textboxes
$(this).val( ui.item.institution_name );
$( 'input[id="InstitutionID['+ index +']"]' ).val( ui.item.id );
$( 'input[id="InstitutionMunicipality['+ index +']"]' ).val( ui.item.municipality );
$( 'input[id="InstitutionProvince['+ index +']"]' ).val( ui.item.province );
return false;
}
})
.data( 'ui-autocomplete' )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append(
'<a class="select-group"><span class="mini-headtitle">' + item.institution_name +
'</span><br/><span class="mini-subtitle">' + item.municipality + '</span></a>' )
.appendTo( ul );
};
}
// target newly added DOM textboxes
setInterval( ajax_connect_to_db, 100 );
How do I make the select box show its content on all dynamically added elements?

try this
function ajax_connect_to_db()
{
$(function() {
.................
});
}

Related

jQuery Autocomplete ComboBox Options Echo'd by PHP Getting Removed when Match Typed

Currently I have a combobox which options gets echo'd by PHP since the values are in an array. The code of the combobox is as follows:
<div class="ui-widget">
Project
<br>
<select id="combobox">
<?php
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
?>
</select>
</div>
What I am trying to achieve is when a user types into the combobox he gets a dropdown-list with all the entries of the array that match the text the user typed in the combobox.
The user can then select an option from the dropdown-list or choose to type the entry completely(but it needs to mach the entries in the dropdown-list).
To achieve all this i am currently using the Autocomplete function of jQuery.
All the code that I am using to achieve this can be watched here: http://jqueryui.com/autocomplete/#combobox.
The code for the combobox I use is as follows:
<script>
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
});
</script>
The problem that I am having right now is when a user types text in the combobox and the dropdown-list appears and he fully types out an entry of the dropdown-list the combobox still gets cleared. This is not supposed to happen. Whenever the user clicks on the combobox the item doesn't get cleared.
To make is a bit clearer here is an image of the combobox:
So above you can see the combobox. Whenever a user types something he gets a dropdown-list with all the results matched(project 1, project 10).
The problem that I am having right now is when a user types out "project 1" without clicking on the item in the dropdown-list the text in the combobox still gets removed by the Autocomplete function in jQuery.
If the user clicks on the item then there is no problem at all.
Funny thing is that the Autocomplete function works without any problems if I don't echo the option elements with PHP.
so:
<option value="project 1">project 1</option>
<option value="project 2">project 2</option>
<option value="project 3">project 3</option>
instead of:
foreach($projects as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
Any help is greatly appreciated.
Change from
echo "<option value=".$value.">".$value."</option>";
TO
echo "<option value='".$value."'>".$value."</option>";

How to keep select after jquery append

Ok guys here's the fiddle
http://jsfiddle.net/wKbXx/24/
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
} else {
$('option[value=' + this.value + ']').remove();
}
});
});
What I need to do is to select two colors with the check boxes. Let say red, and blue. Then using the select, Mark one red and one blue. Then check green. I want it to keep the selected data. Right now once you select green it wipes that data. How can I do that?
UPDATED TO REFLECT WORKING ANSWER.. UPDATED FIDDLE TOO
I would go for a slightly different approach; instead of always resetting the select boxes, I would check whether the text in the changed checkbox is already contained in the select boxes. If it is, I would assume it's been unchecked and remove the option from the select boxes. Otherwise I would append just that new option to the select boxes.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if (sel.find('option').text().indexOf(this.id) > 0) {
$('option[value=' + this.value + ']').remove();
} else {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
});
});
The downside with this version is that the order of the colors in the select boxes is determined by the order in which the checkboxes are clicked; with your version, the order of the colors in the select boxes is always the same as in the checkboxes.
(Hope that made sense.)
Here's a fiddle: http://jsfiddle.net/Niffler/0hLxzvh8/
This may be the answer to your question...
You should have your rewrite on top as well.
$(function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]' ).on( 'change', function() {
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
else {
//Remove where ID matches up
sel.children().remove();
}
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
});
});
Cheers!
You need to get the value of the select box before you replace the options, then reset the value at the end.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.each(function(){
sel.data('previous', sel.val());
});
// overwrite the existing options
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]:checked' ).each( function() {
sel.append( $("<option />").val(this.value).text( this.id ) );
});
// if it had a value, set it back to that.
if ( currentValue != '' ){
sel.each(function(){
sel.val(sel.data('previous'));
});
} else {
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
}
});
});

AutoComplete Highligh Issue

I want to highlight matched characters in jquery autocomplete.
If i type GC,it give me below,which is OK
Green Community
Now i want G and C both to be bold/strong.
$('#9').autocomplete({
source: "auto_loc_name.php",
selectFirst: true,
minLength: 0,
select: function (event, ui) {
alert(ui.item.value);
}
});
I was using JQuery Autocomplete as a combobox and your needs work well with me and you can review the following code may be help you :
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
}
});
})( jQuery );
and I think your needs in the following part but I don't know how to use that in your code :
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
You can try something like this, based on code from jQueryUI: how can I custom-format the Autocomplete plug-in results?
function monkeyPatchAutocomplete() {
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var matchstring = [];
$.each(this.term.split(""), function(index, c){
matchstring.push("^"+c+"|\b"+c);
});
var output = item.label.replace(new RegExp("(" + matchstring.join("|") + ")", "gi"), '<span class="ui-menu-item-highlight">$1</span>');
return $("<li>")
.append($("<a>").html(output))
.appendTo(ul);
};
}
$(function () {
monkeyPatchAutocomplete();
});
May or may not work. The idea is to get a Regex string like ^G|\bG for each character. I'm sure this misses quite a few cases, so keep working on it.
Edit: working jFiddle. http://jsfiddle.net/9MC5M/ Like the code above but with a few bug fixes. The search is deliberatly broken, it just returns all items to showcase the highlighting.

Jquery UI autocomplete link to item

I want to make a search box, where you can search between records in the database.
search.php looks like this:
<?php
// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');
$nameser = $_GET['term'];
$names = array();
$result = mysql_query("SELECT name,customerid FROM customers WHERE name LIKE '%".$nameser."%' ORDER BY name ASC");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['customerid'];
$row_array['value'] = htmlentities($row['name']);
array_push($names,$row_array);
}
echo json_encode($names);
?>
Javascript part looks like this:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
However, this gives the error:
ReferenceError: item is not defined
What I want to happen is, that when I click something in the result list, I get redirected to the url
customers.php?action=view&cid={CustomerID}
Anyone got an idea?
EDIT:
Correct Javascript code that works:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + ui.item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
i have a demo with a working example in jsfiddle. you can see it here:
the key is to get a valid url value in the autoselect select method. be sure to console.log the ui value so you can see what is available for you to use. i was able to use the standard ui.item.value value to send the user to another page.
to test my demo:
1.) go into the input box and enter "a".
2.) select "http://www.utexas.edu"
3.) the new page will load.

jquery autocomplete with php source & json issue

I want to create jquery autocomplete and php, the problem is the data shown in each record of the autocomplete has two values, I managed to do this like this (without PHP),
$(function() {
var authors = [
{
label: "jQuery",
desc: "the write less, do more, JavaScript library"
},
{
label: "jQuery UI",
desc: "the official user interface library for jQuery"
},
{
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine"
}
];
$( "#authorname" ).autocomplete({
minLength: 0,
source: authors,
focus: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#authorname" ).val( ui.item.label );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
now I want to change the source to php page (change authors to "getauthors.php")
I don't know what to put inside "getauthors.php" in order to pass two things for label and desc.
I managed to pass one thing like this using json,
<?php
$json = array();
$json[]="test";
$json[]="test2";
$json[]="test3";
echo json_encode($json);
?>
which outputs like this,
you can see that the second thing is always undefined, how I can pass value to this in php using json (or any other way).
Thanks.
<?php
$json = array();
$json[] = array ("label"=>"test", "desc"=>"description");
...
echo json_encode($json);
?>

Categories