How to remove one particular value in autocomplete? - javascript

$(document).on("click","#Id",function(){
var data = [
{ value: "AL", label: "Alabama" },
{ value: "AK", label: "Alaska" },
{ value: "AZ", label: "Arizona" },
{ value: "AR", label: "Arkansas" },
{ value: "UT", label: "Utah" },
{ value: "VT", label: "Vermont" },
{ value: "VA", label: "Virginia" },
{ value: "WI", label: "Wisconsin" },
{ value: "WY", label: "Wyoming" }
];
$("#Id").autocomplete({
minLength: 0,
source: data,
select: function( event, ui )
{
alert(ui.item.label);
},
})
.data("ui-autocomplete")._renderItem = function( ul, item )
{
if (item.label != "Virginia") {
return $( "<li>" )
.append( "<a>" + item.value + "<br>" + item.label + "</a>" )
.appendTo( ul );
}
};
});
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="test" id="Id">
This is my sample code if i use Virginia am getting empty line but i need the output to be blank.
can anyone solve my issue and provide me an solution

Try this:
$("#Id").data("ui-autocomplete")._renderItem = function( ul, item )
{
if(item.desc != "test"){
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
}
};
instead of uiAutocomplete use ui-autocomplete

Looking at the data on #Id. It looks like its stored under autocomplete.
so, if you have already called
$("#Id").autocomplete({
source: data,
etc : etc
});
then you can call:-
$("#Id").data('autocomplete')._renderItem = function(ul, item) {
if (item.value != "test") {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
}
};
or you can instantiate and set _renderItem like :-
$("#Id").autocomplete({
source: data
}).data('autocomplete')._renderItem = function(ul, item) {
if (item.value != "test") {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
}
};
UPDATE
It looks like different versions of jQueryUI store autocomplete under data differently, as your snippet compared to the version I used are different (autocomplete vs ui-autocomplete).
The issue with the empty line, is a border around the ul. Where the autocomplete thinks is has a value to show, but as you are saying not to render the only value in the autocomplete list then the ul still has the border. By removing the border around the ul will fix this. See the snippet below:-
var data = [{
value: "AL",
label: "Alabama"
}, {
value: "AK",
label: "Alaska"
}, {
value: "AZ",
label: "Arizona"
}, {
value: "AR",
label: "Arkansas"
}, {
value: "UT",
label: "Utah"
}, {
value: "VT",
label: "Vermont"
}, {
value: "VA",
label: "Virginia"
}, {
value: "WI",
label: "Wisconsin"
}, {
value: "WY",
label: "Wyoming"
}];
$("#Id").autocomplete({
minLength: 0,
source: data,
select: function(event, ui) {
alert(ui.item.label);
},
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
if (item.label != "Virginia") {
return $("<li>")
.append("<a>" + item.value + "<br>" + item.label + "</a>")
.appendTo(ul);
}
};
.ui-autocomplete {
border: 0 !important;
}
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="test" id="Id">

Related

How can i put hidden id with autocomplete jquery

I want to put hidden id when get the value from autocomplete for add to database but now when i get value from autocomplete and add to database it's add value is label name not the id of the data
<input type='text' id='id' name='id' class='id_line' placeholder='Item Code'/>
This my jquery code
$("#add_line").on('click',function(){
$('.tbl_add_line').append(data);
$('.id_line').autocomplete({
source: function (request, response){
$.ajax({
url : "<?php echo site_url('warehouse/get_id');?>",
dataType: "jsonp",
data : {
q: request.term
},
success: function( data ) {
response(data);
}
});
},
});
i++;
});
And this is function to get data to show in autocomplete
function get_id(){
$result = "";
if(isset($_GET['q'])){
$code = $_GET['q'];
$this->db->like("item_code",$code)->select('*');
$this->db->order_by("item_code");
$result = $this->db->from("tbl_item_code")->get()->result();
}
$arr = array();
foreach($result as $key){
$arr[] = array(
'id' => $key->id,
'value' => $key->id,
'label' => $key->item_code."(".$key->id.")",
);
}
echo $_GET['callback']."(".json_encode($arr).")";
}
You can use _renderItem method to add custom attributes to created elements.
Try this:
$(function() {
var projects = [{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
}, {
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}, {
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}];
$("#project").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project").val(ui.item.label);
$("#project-id").val(ui.item.value);
$("#project-description").html(ui.item.desc);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
};
});
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-icon {
float: left;
height: 32px;
width: 32px;
}
#project-description {
margin: 0;
p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<div id="project-label">
Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id" disabled>
<p id="project-description"></p>
Fiddle here

Select2.js: why is id the same as text on change for removed?

JSfiddle: http://jsfiddle.net/cjVSj/
I have a simple select2 with the range of possible tags set by the tags option and the preloaded tags set by values in the input field in the html.
When the on change event fires on the select2, the removed item seems to lose its id, reporting instead its text value.
To see the problem, adding a tag (e.g. west) correctly reports the added.id, but removing the existing east tags reports id = east, not 1356.
Any insight into how to gain access to the id of a tag upon removal?
HTML:
<script>
var tags = [{ "id": 1354, "text": "north", "restricted": false
}, {"id": 1355, "text": "south", "restricted": false
}, {"id": 1356, "text": "east", "restricted": false
}, {"id": 1357, "text": "west", "restricted": false
}];
</script>tags:
<input type="text" id="mytags" value="east" />
JS:
$(document).ready(function () {
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id)
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id)
}
});
});
There was an issue with your select2 declaration and syntax.
Further more, if you entered any other text, say "eas" or "test", your piece of code reflected that as it is. Check this scenario.
Updated fiddle: http://jsfiddle.net/ZBf5H/
To be specific, you did not give appropriate mapping to your tags. Please find how to access remote data in select 2 from here
The change of code is as below:
$(document).ready(function() {
var data=[{id:1354,text:'north',restricted:false},
{id:1356,text:'east',restricted:false},
{id:1357,text:'west',restricted:false},
{id:1355,text:'south',restricted:false}];
function format(item)
{ return item.text; }
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
data:{ results: data, text: 'text' },
formatSelection: format,
formatResult: format
});
Let me know if this works for you.
Ok... I've got a working solution, but I still don't exactly understand the difference between select2's tags and data options....
JSfiddle: http://jsfiddle.net/7e8Pa/
I'm initializing select2 with a list of all possible tags via the data option from an array, then selecting those for preloading: the initSelection function checks for ids in the and looks them up in the data array (the pre-stored one, not Select2's). Last, new tags may be added (the createSearchChoice does this). To hook this to my server, I'm just going to insert ajax calls where noted below in the on-change event handler (which gets called after createSearchChoice, and can overwrite the field values for the new object set in createSearchChoice).
JS:
function findWithAttr(array, attr, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i][attr] == value) {
return array[i];
}
}
}
$(document).ready(function () {
function format(item) {
return item.text;
}
$('#mytags').select2({
placeholder: 'Search',
minimumInputLength: 2,
multiple: true,
//tags: tags,
tokenSeparators: [','],
data: {
results: tags,
text: 'text'
},
initSelection: function (element, callback) {
var data = [];
$($('#mytags').val().split(",")).each(function (i) {
var o = findWithAttr(tags, 'id', this);
if (o) {
data.push({
id: o.id,
text: o.text
});
} else {
console.log("findWithAttr returned none; likely invalid id");
}
});
console.log("data = " + JSON.stringify(data));
callback(data);
},
createSearchChoice: function (term, data) {
console.log("create");
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
// call $.post() to add this term to the server, receive back id
// return {id:id, text:term}
// or detect this shiftiness and do it below in the on-change
return {
id: -1,
text: term
};
}
},
formatSelection: format,
formatResult: format
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id);
//modifying the id here overrides what is assigned above in createSelection
e.added.id = 5;
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id);
}
var selections = (JSON.stringify($('#mytags').select2('data')));
$('#selectedText').text(selections);
});
});
HTML:
<script>
var tags = [{
"id": 1354,
"text": "north",
"restricted": false
}, {
"id": 1355,
"text": "south",
"restricted": false
}, {
"id": 1356,
"text": "east",
"restricted": false
}, {
"id": 1357,
"text": "west",
"restricted": false
}];
</script>
<p>tags:
<input type="text" id="mytags" value="1355" style="width:80%" />
</p>
<p>Selected Options: <span id="selectedText"></span>
</p>
<p>Debug: <span id="debug"></span>
</p>

Jquery autocomplete doesn't work

I got the following code from jquery ui demo.
I did some minor modifications to that.
Here is the modified code.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Custom data and display</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!--link rel="stylesheet" href="/resources/demos/style.css"-->
<style>
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-description {
margin: 0;
padding: 0;
}
</style>
<script>
$(function() {
var projects = [
{
id: "jquery",
name: "jQuery",
location: "the write less, do more, JavaScript library"
},
{
id: "jquery-ui",
name: "jQuery UI",
location: "the official user interface library for jQuery"
},
{
id: "sizzlejs",
name: "Sizzle JS",
location: "a pure-JavaScript CSS selector engine"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.name );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.name );
$( "#project-id" ).val( ui.item.id );
$( "#project-description" ).html( ui.item.location );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.name + "<br>" + item.location + "</a>" )
.appendTo( ul );
};
});
</script>
</head>
<body>
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">
<p id="project-description"></p>
</body>
</html>
Now jquery pops up autocomplete suggestions only when 'j' key is pressed.
for other keys it doesn't do anything.
what am I doing wrong here?
It is because of the default search mechanism, it filters the contents based on the fields label or value.
With your custom data, it is better to implement the source method yourself like,
$("#project").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var array = $.grep(projects, function (value) {
return matcher.test(value.id) || matcher.test(value.name) || matcher.test(value.location);
});
response(array);
},
focus: function (event, ui) {
$("#project").val(ui.item.name);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.id);
$("#project-description").html(ui.item.location);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name + "<br>" + item.location + "</a>")
.appendTo(ul);
};
Demo: Fiddle
You must have a value attribute on your projects array:
var projects = [
{
id: "jquery",
name: "jQuery",
value:"jQuery",
location: "the write less, do more, JavaScript library"
},
...
{
id: "sizzlejs",
name: "sizzle JS",
value:"sizzle JS",
location: "a pure-JavaScript CSS selector engine"
}
];
This way the search engine is going to work.

traversing jQuery JSON Object array

I am try access an Object array using getJson, I've tried many things but I keep getting an 'undefined' or [Object, object] returned.
$.getJSON( "js/test.json", function( data ) {
var items = new Array();
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Here is the JSON, I am trying to get the 'title' of each 'entries'.
{
"$xmlns": {
"pl1": "url"
},
"startIndex": 1,
"author": "MJS",
"entries": [
{
"title": "This is target",
"m$ct": [
{
"m$name": "name"
}
],
"m$rt": "pd",
"m$content": [
{
"plfile$width": 640
},
{
"plfile$width": 960
}
],
"plm$c": [],
"link": ""
},
{
"title": "title2",
"m$ct": [
{
"m$name": "name"
}
],
"m$rt": "pd",
"m$content": [
{
"plfile$width": 640
},
{
"plfile$width": 960
}
],
"plm$c": [],
"link": ""
}
]
}
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});
should instead read:
$.each( data.entries, function( key, entry ) {
items.push( "<li id='" + key + "'>" + entry.title + "</li>" );
});
You're iterating over the whole json instead of the entries
It should be data.entries in the each and then just val.title
$.getJSON( "js/test.json", function( data ) {
var items = new Array();
$.each( data.entries, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.title + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

autocomplete searches work, but not gets selected

Input text boxes are created dynamically via jquery. Autocomplete works well. But when I select an item its value is not rendered properly, May I know where am I missing here ?
Jquery
$(function() {
var projects = [
{
"label": "ajax",
"value": "1003",
"desc": "foriegn"
},
{
"label": "jquery",
"value": "1000",
"desc": "dd"
},
{
"label": "wordpress theme",
"value": "1000",
"desc": "h"
},
{
"label": "xml",
"value": "1000",
"desc": "j"
} ];
$("#addButton");
var counter = 13;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'project-description' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'project' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'project-id' + counter
});
newTextBoxDiv.append(roleInput).append(searchInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#project" + counter).autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project" + counter).val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project" + counter).val(ui.item.label);
$("#project-id" + counter).val(ui.item.value);
$("#project-description" + counter).val(ui.item.value);
$("#project-icon" + counter).attr("src", "images/" + ui.item.icon);
return false;
}
})
counter++;
});
});
`
Html is below
<div id="project-label"></div>
<input id="project" />
<input type="hidden" id="project-id" />
<input type="text" disabled="disabled" id="project-description"></p>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="form-inline control-group">
</div>
</div>
<input type='button' value='Add' id='addButton' />
Please tell me what am I missing in this piece of code.
I think it's a JavaScript error. Your select event from the autocomplete looks for $("#project-icon" + counter), but I don't see that element being rendered anywhere. Also, when trying to set the src attribute of that element, you reference ui.item.icon, but your array of values doesn't contain that property.

Categories