jQuery ui autocomplete get selected item in other function - javascript

I have a problem with jQuery autocomplete, I try to get the value of the input but I get the label but no the value.
var listeClients = [{"value":1,"label":"Orange"},{"value":2,"label":"Blue"}];
$( "#site_client_first" ).autocomplete({
source: listeClients,
select: function (event, ui) {
$("#site_client_first").val(ui.item.label);
return false;
}
And for get the value I use :
$("#site_client_first").val();
https://jsfiddle.net/fyz8vL3a/
How to get the value ?
Thanks by advance =)

In the select event of autocomplete, you are setting the label as value property of element #site_client_first i.e. here $("#site_client_first").val(ui.item.label). Hence when you try to set the span's innerHTML by assigning $("#site_client_first").val(), you will always get the label and not your item.value.
Try the code below. I have added an attribute 'itemValue' to $("#site_client_first"). This will hold your item's value and $("#site_client_first").val() will hold the item's label.
And when setting up the span innerhtml, you assign $("#site_client_first").attr("itemValue") which is your item's value.
<input class="form-control" name="site[client]" id="site_client_first" itemValue="100" />
Make change to the above line in your HTML change.
Your final html is as belows:
<input class="form-control" name="site[client]" id="site_client_first" itemValue="100" />
<button onclick="getValue()">Get</button>
<span id="svalue"></span>
Your script goes here:
$(document).ready(function() {
var listeClients = [{ "value": 1, "label": "Orange"}, {
"value": 2,
"label": "Blue"
}];
$("#site_client_first").autocomplete({
source: listeClients,
select: function(event, ui) {
$("#site_client_first").val(ui.item.label);
$("#site_client_first").attr("itemValue", ui.item.value);
return false;
}
});
})
var getValue = function() {
document.getElementById("value").innerHTML = $("#site_client_first").attr("itemValue");
}
function getValue() {
document.getElementById("value").innerHTML = $("#site_client_first").attr("itemValue");
}

The problem is you are trying to use an input element as a select element.
Unlike for a select, the value for an input is simply what is written in it.
The default behavior of the autocomplete plugin is to display the labels of given source as suggestions, and when you select one them it sets the corresponding value in the input. You are overriding this functionality in the code below, by setting the label as value of the input:
select: function (event, ui) {
$("#site_client_first").val(ui.item.label);
return false;
}
If you were to remove the piece of code above, you would notice that the value field will be written in the input element upon selection of an option.
Solution 1
I recommend replacing your input element with a select one. Which I think better suits your needs. If you need to search through the options you may want to use a plugin like chosen or select2.
Solution 2
If you're keen on using an input with autocomplete, set the value as an extra attribute in the select callback
select: function (event, ui) {
$("#site_client_first").val(ui.item.label); // what the user sees
$("#site_client_first").attr('data-realValue', ui.item.value); // value is hidden
return false;
}
You can retrieve the value using
$("#site_client_first").attr('data-realValue');
Demo: https://jsfiddle.net/fyz8vL3a/1/

Related

How to filter a JSON array in autocomplete jquery and show a dynamic value in JavaScript?

I have successfully implemented the jQuery Autocomplete function in my HTML input filed, it returns an array of JSON objects, what I would like to achieve is the following:
click on an item of the dropdown list
filter such item's string to get only the objID string.
So, here's my js code:
$.ajax({
url: "<?php echo $pointerClass ?>.json",
type: "POST",
dataType: "JSON"
}).done(function(data){
var jsonData = data;
var arr = new Array();
var keys = Object.keys(jsonData);
for(var i=0; i<keys.length; i++){
var key = keys[i];
var jString = JSON.stringify(jsonData[key]);
arr.push(jString);
}// ./ for
console.log('arr: ' + arr[0]);
// autocomplete jquery function
$( "#ar-type-pointer-objID" ).autocomplete({
source: arr,
minLength: 1
});
});
Here's a screenshot of my drop-down menu:
As you can see by the red frame, I need to click on an item and pass only the "objID" value to my input field, so it'll be "qO19zg8mV4" since I'm clicking on the row in the red square.
Here's how my input should look like after clicking on a drop-down's row:
According to the autocomplete documentation, you have two interesting events: select and close.
select is
Triggered when an item is selected from the menu. The default action is to replace the text field's value with the value of the selected item
close is:
Triggered when the menu is hidden. Not every close event will be accompanied by a change event.
Select has two parameters:
event
ui
ui is an object like this:
item: {
label: string,
value: string
}
Not sure where you will get your JSON, probably value, so I assume that...do a console.log to be sure of it!
You should rewrite with something like
$( "#ar-type-pointer-objID" ).autocomplete({
source: arr,
select: function(event, ui) {
const target = event.target;
const val = JSON.parse(ui.item.value); // Check if decode is needed or is already passed as an object
jQuery(target).val(val.ObjID);
event.preventDefault();
return false;
}
});
We prevent the default, because "The default action is to replace the text field's value with the value of the selected item." and your change in the input field will be lost.
You still have to manage some info by yourself but the idea should be enough!

Getting the value of a hidden field in <td> using jquery

I have a table data which is generated dynamically via a loop. The td contains a hidden field. below is the code for the same:
<td class="gridtd" id = "r<%=RowNumber%>c<%=ColumnNumber%>">
<input id="hiddendata" type="hidden" value="<%: item.Key%>"/>
</td>
I need to extract the value of the hidden field based on the td selected using jQuery. Please help me get the correct jquery code.
Just select your input and take the value (val()):
$("#hiddendata").val();
If you want to take all hidden input values:
$("input[type='hidden']").each(function () {
console.log($(this).val());
});
Note that the element ids must be unique.
I need to extract the value of the hidden field based on the td selected using jQuery.
If by select you mean, click, you can simply pass this when getting the value:
$("td").on("click", function () {
console.log(
$("[type='hidden']", this).val()
);
});
For your general knowledge, if you do $("#hiddendata", this).val(); inside of the click handler, it will return the correct value (even having multiple ids with the same value).
But definitely, the ids must be unique.
Use this :
$('#hiddendata').val();
$('td').click(
function(event)
{
$(event.target).find('#hiddendata').val();
}
);
It ll give the hiddendata value based on td selection
This will give the value of the hidden field for the selected td.
$('.gridtd').click(function(){
console.log($(this).find('input').val());
});
$('.gridtd').click(function(){
console.log($(this).find('input[type=hidden]').val());
});
You can try this:
$('.gridtd').each(function(){
var currentId = $(this).attr('id');
var hiddenval = $('#'+currentId).find('input[type=hidden]').val();
alert(hiddenval);
})

jquery clone an input doesn't see changes to the value

I have a form with hidden inputs.
I .clone() them and show them to the user in a .dialog().
The user makes some changes and i use .val() to change the hidden fields.
However the next time i clone the form(without reloading the page) i have the initial values again, and never the updates ones.
There seems to be this weird bug/result? see http://jsfiddle.net/YvBfP/ (broken for visible input too)
$(this).closest('td').find('button').click( function ()
{
var d = $('#pagamento_anticipato').html();
$(d).dialog({
modal: true,
width: 400,
height: 300,
close: function( event, ui ) {
var importo = $(this).find('input[type="text"]').val();
var descrizione = $(this).find('textarea').val();
var select = $(this).find('select').val();
$(this).remove();
$('#pagamento_anticipato').find('input[id="importo"]').val( importo );
$('#pagamento_anticipato').find('#descrizione').val( descrizione );
$('#pagamento_anticipato').find('#tipo').find('option[value="' + select + '"]').attr('selected', true);
}
});
return false;
});
using .val() sets/gets the current value and not the attribute for the element.
$(element).val(value) // sets current value
$(element).val() // <-- will always return the current value
to change the attribute you have to use .attr()
$(element).attr('value',value)
Then you will see the change in the HTML
http://jsfiddle.net/wirey00/bJjjw/
EDIT:
Just found out this doesn't work with jQuery 1.5.x and lower.. tested it with jQuery 1.6.0+ and it worked fine
You are setting the value property of the input but checking to see if the value attribute has changed. To see the elements value use .val() don't check its html. However if you need to change the elements value attribute use setAttribute
$('#money')[0].setAttribute('value', 3000);
http://jsfiddle.net/YvBfP/4/

How to match multiple substrings in jQuery combobox autocomplete

I found more than a couple examples of this with a plain jquery autocomplete but not in a way that will work with the autocomplete included in the combobox code from the demo because the structure of the code is structured so differently.
I want to match every item that has all of the search tokens anywhere in any word. I don't need to match the start of any word, any part of it is fine. I don't care if the search strings are highlighted in the autocomplete list if that makes things too complicated.
Desired search/result combos: (please excuse the spacing)
"fi th" "fi rst second th ird"
"rs on" "fi rs t sec on d third"
"ec rd" "first s ec ond thi rd"
but not limited to any max/min length or number of tokens.
EDIT
I figured part of it out using the code structure from the other autocorrect I had working.
source: function( requestObj, responseFunc ) {
var matchArry = $("select > option").map(function(){return this.innerHTML;}).get();
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches
$.each (srchTerms, function (J, term) {
var regX = new RegExp (term, "i");
matchArry = $.map (matchArry, function (item) {
if( regX.test(item) ){
return{
label: item,
value: item,
option: HTMLOptionElement
} ? item :null;
}
} );
});
// Return the match results
responseFunc (matchArry);
},
and
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
$("destination").val(ui.item.value); // I added this line
},
but I can't get both multiple words AND being able to click to select working at the same time.
If I remove the } ? item :null; on the return in the map function I can click to select an item. If I leave it I can type multiple words, but I can't click any of the items...
Is that the problem or the option: this? I've tried replacing it with HTMLOptionElement and null and I'm stuck.
I am able to set the value of another field with ui.item.value within the select label but that doesn't put the value in the search box or close the dropdown menu.
On a whim I added ui.item.option = ui.item.value; to the select label and everything works as expected. the option: value in source doesn't seem to matter now.
*I make no claims that any of this is good coding practice
updated fiddle: http://jsfiddle.net/eY3hM/

jquery, javascript, update dropdown list options upon focus but retain selected value

Brain not working right now. Someone help me fill in the blanks here.
Need to select the currently selected value, repopulate the options, and then select the previous selection if it's still in the list.
To make it easier, the new value and previously selected value will have the same name attribute assuming it's still in the list after updating, and names will always be unique for the list of options.
//assume Options is a globally defined var for this example with format:
// [{"display":"something", "value": "something's value"}, etc.. ]
function LazyLoadOptionsIntoSelect($select, options)
{
//get current option
//repopulate options
$select.html("");
$("<option>").text("--Select a File--")
.appendTo($select);
$.each(options, function()
{
var item = this;
$("<option>").attr("name", function () { return item.display; })
.val(function () { return item.value; })
.text(item.display)
.appendTo($select);
});
//select previously selected option if still in list
}
$(".lazyloadedselect", "#context").live("focus", function()
{
LazyLoadOptionsIntoSelect($(this), Options);
});
EDIT: mistake in my code, unrelated to the problem, but still wrong
If the option retains the same value attribute:
//get current option
var theOption = $select.val();
And later...
//select previously selected option if still in list
$select.val(theOption);
EDIT
You'll need to fix an error in your population code because none of those options actually have value attributes, which is probably why you can't properly set the value of the select:
$.each(options, function(index, item) {
$("<option>")
.attr("value", item.display)
.text(item.display)
.appendTo($select);
});
Please note name is not a standard attribute for an option element.

Categories

Resources