Adding title attribute to select option dynamically with .append() - javascript

Javascript, Jquery, HTML
I am adding select options to a select box dynamically. I take each unique element in an array and add it as an option to the select element. It works great, but I need to add a title attribute at the same time, with the same value as the option text. The end goal of this is to make tooltips for each option.
So instead of <option>value</option>, it looks like
<option title="value">value</option>
Does that make sense?
Current HTML:
<select id="Process_Issue" class="fieldLabel2 IncidentInputField dynamicFields1"></select>
JS:
$.each(eliminateDuplicates(aryProcess), function (key, value) { $('#Process_Issue').append($("<option/>", { text: cleanNulls(value) })); });

You can just specify the title upon appending:
JSFiddle
HTML
<select id="my_select"></select>
JS
$('#my_select').append('<option title="value1">value1</option>');
$('#my_select').append('<option title="value2">value2</option>');
$('#my_select').append('<option title="value3">value3</option>');

You can set the title attribute
$('#Process_Issue').append(
$("<option/>", { text: value }).attr("title",value)
);
Here is a working sample http://jsbin.com/ozudoTod/1/

You seem to be using the same selector multiple times for each iteration in the array. Instead cache it and save some lookup time.
var $select = $('#Process_Issue');
$.each(eliminateDuplicates(aryProcess), function (key, value) {
var val = cleanNulls(value);
$select .append($("<option/>", {
text: val,
title: val
}));
});
If this does not work use .attr method to hook up the attribute to the element.
var $select = $('#Process_Issue');
$.each(eliminateDuplicates(aryProcess), function (key, value) {
var val = cleanNulls(value);
$('<option/>').attr({
text: val,
title: val
}).appendTo($select);
});

A cleaner way is to create the element before with all values then append like so:
value = cleanNulls( value );
var option = $( '<option/>', {
title: value,
text: value
});
$('#Process_Issue').append( option );
this method is a lot cleaner and easier to read / maintain

Related

jQuery ui autocomplete get selected item in other function

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/

How to clear a selected value in Selectize.js dropdown?

I have a selectize.js dropdown and I have to clear the selected value .
I have tried this (as suggested in another question):
var selectize = $("#optionNetFlow")[0].selectize;
selectize.clear();
But it gives the following error:
When I change it to this:
var selectize = $("#optionNetFlow").selectize;
selectize.clear();
I gives this error:
What I am doing wrong here?
I finally found the answer here Selectize.js Demos
What works for me is:
var $select = $('#optionNetFlow').selectize();
var control = $select[0].selectize;
control.clear();
what I was missing var $select = $('#optionNetFlow').selectize(); before applying the solution provided in above question's answer.
Now I am to get all the functions in console like :
Try this,
$("#optionNetFlow")[0].selectize.clear();
Try this out:- http://jsfiddle.net/adiioo7/2gnq1ruv/204/
JS:-
jQuery(function ($) {
var $select = $('#input-tags').selectize({
persist: false,
create: true
});
$("#btnClear").on("click", function () {
var selectize = $select[0].selectize;
selectize.clear();
});
});
All other answers either clear a single selectize or need a specific reference to the selectize in the moment of it's creation.
The solution below, on the other hand, works for any number of selectize elements you have inside any form; you just need to specify the desired form:
$('form').find('.selectized').each(function(index, element) { element.selectize && element.selectize.clear() })
The rationale is that Selectize keeps the original element in the DOM (hiding it), adds a reference to the selectize on the .selectize property of the DOM element and adds a CSS class selectized to it.
So the solution finds all the elements that have the CSS class selectized, loops through them and calls element.selectize.clear().
$(document).on('click', 'div.selectize-input div.item', function(e) {
var select = $('#services').selectize();
var selectSizeControl = select[0].selectize;
// 1. Get the value
var selectedValue = $(this).attr("data-value");
// 2. Remove the option
select[0].selectize.removeItem(selectedValue);
// 3. Refresh the select
select[0].selectize.refreshItems();
select[0].selectize.refreshOptions();
});
This do not remove the item from the select, just remove it from the selected options.
Or if you have multi select, and do want to restore selected items in the drop-down list (hide selected set to true).
var selectize = $("#select-item").selectize;
//clone array
var items = selectize.items.slice(0);
for (var i in items) {
selectize.removeItem(items[i]);
}
selectize.refreshOptions();

Jquery populate multiple select boxes with the same name

I am dynamically creating elements with javascript that end up looking something like this:
<select id="splitUserDDL" name="splitUserDDL[]"></select>
When I attempt to add options, it seems that the first select box is being populated but not the rest. Is there a way that I can add the same options to all of the select boxes?
$('#splitUserDDL').empty();
var userDDL = document.getElementById('splitUserDDL');
var defaultoption = document.createElement('option');
defaultoption.text = '-Select-';
defaultoption.value = 0;
userDDL.add(defaultoption);
Use a class instead of ID.
<select class="splitUserDDL" name="splitUserDDL[]"></select>
Then use jQuery to add the option, and loop over all of them:
$(".splitUserDDL").empty();
$(".splitUserDDL").each(function() {
$(this).append($("<option>", {
text: "-Select-",
value: 0
});
});

Select2 Dropdown Dynamically Add, Remove and Refresh Items from

This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)
i have a select2 which gets data from a ajax call.
<input id="valueg" type="hidden" style="width: 300px;" data-placeholder="Select a Conference" />
$("#valueg").select2({
data: conferences,
allowClear: true,
initSelection: function (element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
}
}).on("change", function (e) {
// show data in separate div when item is selected
});
Can some one provide a clear method how to delete and add an item from the Select2.
For example:
I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.
I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.
From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:
$('#valueg').select2('val', 'YOUR_VALUE');
In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:
var el = $('select[name="type"]', '#details-form');
var temp = el.select2('val'); // save current value
temp.push(NEW_VALUE); // append new one
var newOptions = '<option value="1">1</option><option value="2">2</option>';
el.select2('destroy').html(newOptions ).select2().select2('val', temp);
I did it this way:
var $select2 = $('#valueg').select2(); // getting the select2
var item = 'xyz'; // item to be added
$select2.val(function(i, val) { // val can take function as parameter
val = val || []; // if value is null init val as an array
val.push(item); // add the new item
return val;
}).trigger("change"); //refresh
Hope that helps
I had the same issue. This is how i solved it
This has nothing to do with select2, manipulating the itself seems to work for me
$("#lstService").empty();
for(var i=0;i<data.length;i++){
$("#lstService").append('<option value="'+data[i].service_id+'">'+data[i].service_name+'</option>');
}
In my case, the key thing to add after manipulating the underlying select is:
$selectlist.trigger("change"); //$selectlist is the underlying select element.
Select2 works around the change event on a select, so calling "change" updates the option displayed in the select 2.
It is too late... but this is my solution for people that still have this problem:
html = "";
jQuery("#select_2 option").each(function()
{
html += '<option value="'+jQuery(this).attr("value")+'">'+jQuery(this).text()+'</option>';
});
html += '<option value="NEWVALUE">NEW OPTION</option>';
jQuery("#select_2").html(html);

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