jQuery Tooltip on Selectize - javascript

I am trying to add a jQuery tooltip on a Selectize (http://brianreavis.github.io/selectize.js/) select box, however for some reason I'm having some problems.
Here's a snippet of my code:
$(function() {
$("#myDropdown").selectize({
onChange: function(value) {
var ddOptions = {
1: triggerOpt1,
2: triggerOpt2,
3: triggerOpt3,
4: triggerOpt4
};
ddOptions[value]();
},
render: {
option: showItem,
item: showItem
}
});
$("#myDropdown .ddOption").tooltip({
position: "bottom left",
offset: [-2, 10],
opacity: 0.9
});
});
function showItem(data) {
return Handlebars.templates["dropdown"]({
itemClass: data.value,
label: data.text,
title: I18n["ddOption_" + data.value]
});
}
<select id="myDropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
For some reason, I am not getting the jQuery tooltip but the native browser tooltip. When I try to attach the tooltip in the console it works fine..
Has anyone ever encountered this issue?
EDIT: the class ddOption is being added to the selectize items in the handlebars template.

I don't know about Selectize but I can figure out it is based on jQuery-ui's selectmenu with which I experienced same problem.
The underlying cause is that jquery-UI hides actual select element and build an entirely new one with other html which simulates it and synchronize its value to original select tag.
So, if you capture it, for example, by it's id or class to do anything, you end up modifying a hidden element.
You should search for a sibling span with the ui-selectmenu-button class instead. But better use your preferred browser inspector to see it's actual attributes uses selectize plugin.

ddOptions is JS array type.. you need html element to get hover intent..
so try below code .. it might help you out...
$("#myDropdown option").tooltip({
position: "bottom left",
offset: [-2, 10],
opacity: 0.9
});
});

I found a partial solution:
Only apply if you tooltip message is generic or equals, to each elements that take Selectize plugin in the View.
Use jQuery to set manually ToolTip options:
$(".selectize-control").tooltip({
placement: "top", // position
title: "Your Message"
});

I've created this code. I hope it helps you.
This is the way like I initialized my data to Selectize
$.ajax({
type: 'GET',
url : 'tableConfig',
success : function(data) {
$('#idTrans').each(function() {
if (this.selectize) {
let list = data.filter(x => x.codigo === "TRANS");
for(let i = 0; i < list.length; i++){
this.selectize.addOption({value:list[i].idConfiguracion, text: list[i].valor, title: list[i].descripcion});
}
}
});
},
error: function (request, status, error) {
//alert("No se pudo realizar la operaciĆ³n por un error interno, contactese con el Administrador.");
}
});
And then, I can customize the tooltip.
$('#idTrans').selectize({
render: {
option: function(data, escape) {
let txtTitle = data.title;
if(txtTitle === undefined || txtTitle === 'Ingrese Detalle:') txtTitle = '';
return '<div class="option">' +
'<div title="' + txtTitle + '">' + escape(data.text) + '</div>' +
'</div>';
},
item: function(data, escape) {
return '<div>'+ escape(data.text) + '</div>';
}
},
onChange: function (value) {
let tableConfig = $('#tableConfig').bootstrapTable('getData');
let list = tableConfig.filter(x => x.idConfiguracion === parseInt(value));
if (list.length > 0) {
let idProTrans = list[0].nivel_padre;
if (idProTrans !== null) {
$("#idProceso_Trans").val(idProTrans);
}
}
}
});
The property 'onChange'. Maybe, it isn't necessary for you and also you can delete that part.As you see, inside of render's property. I put 'title' for tooltip
Finally, looks like this.

Related

How to show selected options from dropdown in javascript

Hi guys i have written some javascript code to display some values depend on another dropdown. So now i would like to display those selected values in my edit page..
Here is my code:
function getSubjectsTopics(subject_id)
{
if(subject_id) {
loading_show();
axios.get("/master/topic/get-topic-by-subject-id/" + subject_id)
.then(function(response) {
var optionHtml = '<option value="0">Parent</option>';
if(response.data.status) {
$.each(response.data.subject_topics, function(i,v) {
optionHtml += `<option value="${v.id}" >${v.name}</option>`;
}
$("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
loading_hide();
})
.catch(function(error) {
loading_hide();
console.log(error);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!'
})
})
} else {
$("#ddl_topic_type").attr('disabled', true);
}
}
Can some one help me how can i add my selected code in optionhtml variable.TIA
In the $.each block, you can use a ternary operator and add the "selected" keyword based on the selection criteria.
First assign a boolean to isSelected variable after checking whether it should be selected or not. Then add the selected keyword into the template literals using a ternary operator
optionHtml += `<option value="${v.id}" ${isSelected ? 'selected' : ''} >${v.name}</option>`;

HTML select not refreshing after being populated via JQuery

I've been using JQuery to populate a drop down list on the click of a HTML select element. The options get created however on the first click the options get shown in a very small box with a scroll. see below
incorrect
If I then close and reopen the dropdown it appears correctly. as below.
correct
It feels like the dropdown list is appearing before jquery has rendered the new options elements. I've tried to find away to re-render it but with no luck.
This feels like it should be such an easy fix but I'm new to scripting and struggling.
HTML
<select class="custom-select" id="templateGroupName" name="templateGroupName">
<option selected>Please Select a group</option>
</select>
JS - Wrapped in document.ready
$('#templateGroupName').click(function () {
$.ajax({
type: "GET",
url: '/Layout/GetGroups',
success: function (data) {
helpers.buildDropdown(
data,
$('#templateGroupName'),
'Select an option'
);
}
});
});
var helpers =
{
buildDropdown: function (result, dropdown, emptyMessage) {
// Remove current options
dropdown.html('');
// Add the empty option with the empty message
dropdown.append('<option value="">' + emptyMessage + '</option>');
// Check result isnt empty
if (result != '') {
// Loop through each of the results and append the option to the dropdown
$.each(result, function (k, v) {
dropdown.append('<option value="' + v.Id + '">' + v.Name + '</option>');
});
}
}
}
First, you need a <select> as the parent, not an empty element,
dropdown = $('#templateGroupName');
then insert it as a document element, not a string:
var opt = document.createElement('option');
opt.value = v.Id;
opt.innerHTML = v.Name;
dropdown.appendChild(opt);
The browser gets confused when you inject options while the <select> is open. To be fair, your users would probably be confused too.
If you're waiting for something to load, tell them to wait.
If something isn't usable, disable it.
Putting these two together: the first time a user hovers over the <select>, disable it and set the cursor to a loading wheel. Wait until your data loads, then insert the options, re-enable it and switch the cursor back.
var helpers = {
buildDropdown: function(result, dropdown, emptyMessage) {
dropdown.html('');
dropdown.append(`<option value="">${emptyMessage}</option>`);
if (!!result) {
$.each(result, function(k, v) {
dropdown.append(`
<option value="${v.Id}">
${v.Name}
</option>
`);
});
}
}
}
const $DROPDOWN = $('#templateGroupName');
// using jQuery#one to only fire the click event once
$DROPDOWN.one('mouseenter', _ => {
// disable dropdown while loading options
$DROPDOWN.attr('disabled', true)
console.log('loading options...');
// replace contents with your GET request
setTimeout(function() {
helpers.buildDropdown(
Array.from({
length: 30
}, (_, i) => ({
Id: i,
Name: i
})),
$DROPDOWN,
'Select an option'
);
// un-disable after options are loaded and inserted
$DROPDOWN.attr('disabled', false)
}, 1000);
})
/* Show "loading" wheel while loading */
select.custom-select[disabled] {
cursor: wait;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="custom-select" id="templateGroupName" name="templateGroupName">
<option selected>Please Select a group</option>
</select>

Dynamically set select2 options with formatting

Select2 v4.0 lets you add options to the dropdown dynamically by creating new Option objects and appending them. How can you dynamically add data which has more than just an id and text?
More specifically, if the select2 uses the templateResult configuration to style data with more than just plain text then adding Options is too restrictive. This callback only works with the library's own data format.
$('#select2').select2({
templateResult: function(data) {
return data.text + ' - ' + data.count;
}
});
$('#select2').append(new Option('Item', 1, false, false));
I'd like to add more complex data when the dropdown is opened and template the results.
I've tried some ugly workarounds, such as
var opt = new Option('Item', 1, false, false);
opt.innerHTML = '<div>Item</div><div>Count</div>';
But the HTML gets stripped and select2 displays plain text.
The library's maintainer states there is not going to be any support for this feature, as reported in a closed Github issue . The only reasonable workaround I've found is to re-initialize the element after it's populated:
function initSelect2(data) {
var select = $('#select2');
select.select2({
templateResult: function(data) {
return data.text + ' - ' + data.count;
});
if (data.length) {
select.data('loaded', 1);
select.select2('open');
} else {
select.on('select2.opening', fillSelect2);
}
function fillSelect2() {
var select = $('#select2');
if (select.data('loaded')) {
return;
}
var data = [];
var data.push({id: 1, text: 'One', count: 1});
var data.push({id: 2, text: 'Two', count: 2});
var data.push({id: 3, text: 'One', count: 3});
initSelect2(data);
}
initSelect2();
Maybe just using the standard html/jQuery and customize whatever you need.
$('#select2').append("<option value='"+ id +"'>" + text+ "</option>");

JQuery set select box value to selected

Please help i am doing this to use in my mobile with jquery mobile
var obj = jQuery.parseJSON(finalresult);
//alert(obj);
var dept = '2';
$(document).ready(function () {
//$("#opsContactId").empty();
$.each(obj, function (k, v) {
var $opt = $("<option/>");
$opt.attr("value", k);
//alert(k);
//alert(v);
//var value1=v;
if (k == dept) {
//$opt.attr("selected","selected");
//alert("in if");
$("#opsContactId").val(k);
//document.getElementById("opsContactId").value=k;
// $('#opsContactId').selectmenu('refresh', true);
}
$opt.text(v);
$opt.appendTo($("#opsContactId"));
});
});
not able to set an option to be selected by dafault
As others as stated, jQuery's .prop() would be the most suitable answer here as jQuery Docs mention themselves:
"The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value."
To further your on your example, jQuery allows for method 'chaining' which returns the jQuery object after the method has completed, thus you can add another method directly after it.
<select id="opsContactId">
</select>
<script>
$(document).ready(function() {
var tmp = [ 1, 2, 3, 4, 5 ],
dept = 2;
$.each( tmp, function( k, v ) {
$("<option/>").attr("value", k)
.text( "Value - " + v)
.appendTo( $("#opsContactId") )
.prop( 'selected', ( k == dept ? 'selected' : '' ));
});
});
</script>
Fiddle: http://jsfiddle.net/twdgC/
Later I forgot you mentioned the jQuery mobile aspect of your question, which changes the dynamic of the question a little bit. The snippet above is run after the page has loaded (Thus, all the jQuery mobile attachments have already been set/made), which would happen to give you the result of (below)
Fiddle: http://jsfiddle.net/5ksG8/
This obviously isn't helpful when trying to construct an <select> list, thus we'll need to append the snippet above with:
$("#opsContactId").selectmenu('refresh', true );
After the snippet has run, thus it 'reloads' the entire list, finally providing you with (below)
Fiddle: http://jsfiddle.net/YxVg6/
You were doing this in your original snippet, the issue was - you were executing it within the loop (And it was commented out!).
Would something like this not be easier?
Would something like this not be easier?
var selected = "selected"; // work this out
var text = "Option Text"; // work this out
var value = "Option Value"; // work this out
$("#opsContactId").append('<option value="' + value + '" '+ selected + '>' + text + '</option>');
jsBin demo
if you have a match you'll need to add the attribute selected. however I don't know how your object looks like...
var obj = {"1":"one","2":"two","3":"three","4":"four"}; // let's say that's how it looks
var dept = '2';
$(function () {
var $sel = $("#opsContactId");
$.each(obj, function (k, v) {
var $opt = $("<option/>", {value:k, text:v}).appendTo( $sel );
if (k == dept) $opt.prop({selected:true});
});
});

Adding options to a <select> using jQuery?

What's the easiest way to add an option to a dropdown using jQuery?
Will this work?
$("#mySelect").append('<option value=1>My option</option>');
Personally, I prefer this syntax for appending options:
$('#mySelect').append($('<option>', {
value: 1,
text: 'My option'
}));
If you're adding options from a collection of items, you can do the following:
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
});
This did NOT work in IE8 (yet did in FF):
$("#selectList").append(new Option("option text", "value"));
This DID work:
var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.
$('#select').append($('<option>', {value:1, text:'One'}));
$('#select').append('<option value="1">One</option>');
var option = new Option(text, value); $('#select').append($(option));
If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
This is very simple:
$('#select_id').append('<option value="five" selected="selected">Five</option>');
or
$('#select_id').append($('<option>', {
value: 1,
text: 'One'
}));
Option 1-
You can try this-
$('#selectID').append($('<option>',
{
value: value_variable,
text : text_variable
}));
Like this-
for (i = 0; i < 10; i++)
{
$('#mySelect').append($('<option>',
{
value: i,
text : "Option "+i
}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
Option 2-
Or try this-
$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );
Like this-
for (i = 0; i < 10; i++)
{
$('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
That works well.
If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.
for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+
I had to use $("#myselect").html("<option value='text'>text</option>");
To help performance you should try to only alter the DOM once, even more so if you are adding many options.
var html = '';
for (var i = 0, len = data.length; i < len; ++i) {
html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}
$('#select').append(html);
Why not simply?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
Test here:
for (let i=0; i<10; i++) {
$('<option/>').val(i).text('option ' + i).appendTo('#mySelect')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect"></select>
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
I like to use non jquery approach:
mySelect.add(new Option('My option', 1));
var select = $('#myselect');
var newOptions = {
'red' : 'Red',
'blue' : 'Blue',
'green' : 'Green',
'yellow' : 'Yellow'
};
$('option', select).remove();
$.each(newOptions, function(text, key) {
var option = new Option(key, text);
select.append($(option));
});
You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot
Output:
var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
var myselect = $('<select>');
$.each(resultData, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<select id="selectCity">
</select>
Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:
var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);
If you want to insert the new option at a specific index in the select:
$("#my_select option").eq(2).before($('<option>', {
value: 'New Item',
text: 'New Item'
}));
This will insert the "New Item" as the 3rd item in the select.
There are two ways. You can use either of these two.
First:
$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');
Second:
$.each(dataCollecton, function(val, text) {
options.append($('<option></option>').val(text.route).html(text.route));
});
You can append and set the Value attribute with text:
$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));
How about this
var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);
if u have optgroup inside select, u got error in DOM.
I think a best way:
$("#select option:last").after($('<option value="1">my option</option>'));
We found some problem when you append option and use jquery validate.
You must click one item in select multiple list.
You will add this code to handle:
$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");
$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected
$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected
$(function () {
var option = $("<option></option>");
option.text("Display text");
option.val("1");
$("#Select1").append(option);
});
If you getting data from some object, then just forward that object to function...
$(function (product) {
var option = $("<option></option>");
option.text(product.Name);
option.val(product.Id);
$("#Select1").append(option);
});
Name and Id are names of object properties...so you can call them whatever you like...And ofcourse if you have Array...you want to build custom function with for loop...and then just call that function in document ready...Cheers
Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select id="selectCity"></select>
Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!
If someone comes here looking for a way to add options with data properties
Using attr
var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);
Using data - version added 1.2.3
var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);
$('#select_id').append($('<option>',{ value: v, text: t }));
This is just a quick points for best performance
always when you are dealing with many options, build a big string and then add it to the 'select' for best performance
f.g.
var $mySelect = $('#mySelect');
var str = '';
$.each(items, function (i, item) {
// IMPORTANT: no selectors inside the loop (for the best performance)
str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string
$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');
Even faster
var str = "";
for(var i; i = 0; i < arr.length; i++){
str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}
$mySelect.html(str);
$mySelect.multiSelect('refresh');
This is the way i did it, with a button to add each select tag.
$(document).on("click","#button",function() {
$('#id_table_AddTransactions').append('<option></option>')
}
You can do this in ES6:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
});
Try
mySelect.innerHTML+= '<option value=1>My option</option>';
btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
<button id="btn">Add option</button>
<select id="mySelect"></select>
U can try below code to append to option
<select id="mySelect"></select>
<script>
$("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
</script>

Categories

Resources