We want to make a new select box and copy its options from another select box when an event happens. We use below code:
//Create a new select box and add it to a div
$('#content').append("<select id='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$("#destination").append($options);
http://jsfiddle.net/e8ctkkvL/1/
I have a page with lots of selects(each with lots of options), above code is slow ! Is there any way I can make above JS faster ?!
I'd rather copy the source and set a dynamic id since you may want to have multiple select boxes and different IDs, like below:
Demo#Fiddle
$(document).ready(function () {
var id = 1;
$("#btn").click(function () {
//Create a new select box
$('#content').append($("#source").clone(true).attr({id: "destination" + id}));
id++;
});
});
You should set a class instead of an ID and then append it to the last created select, for example:
$(document).ready(function () {
$("#btn").click(function () {
//Create a new select box
$('#content').append("<select class='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$(".destination").last().append($options);
});
});
Fiddle: http://jsfiddle.net/e8ctkkvL/3/
Related
I am dynamically generating a select contol with jQuery on my page. The generated select is given below.
<select id="autoCompleteSelect" size="5" class="autoSelect">
<option value="firstVal">firstVal</option>
<option value="secondVal">secondVal</option>
</select>
Now i want to select the first item of this select control on my textbox keyup event. But i cannot do so. The keyup code is -
$('#searchInput').keyup(function (e) {
var a = $(".autoSelect").val();
var myDDL = $('.autoSelect');
myDDL[0].selectedIndex = 0;
});
however when i do not generate select dynamically and just put it on the page from the beginning. Everything works fine. What could be the solution for dynamically generated select.
$("#autoCompleteSelect").val($("#autoCompleteSelect option:first").val());
http://jsfiddle.net/oob1ybxp/
If working with dynamically generated content, it is best to use event delegation concept like below:
// document here can be replaced with closest parent which
// created/ existed without dynamic load
// provided context parameter to on function
$(document).on('keyup','#searchInput', function (e) {
var a = $(".autoSelect").val();
var myDDL = $('.autoSelect');
myDDL[0].selectedIndex = 0;
});
Read this .on() also.
Keep your code in the form something like
$('someStaticSelector').on('keyup', 'DynamicAddedSelector', function (e) {
var a = $(".autoSelect").val();
var myDDL = $('.autoSelect');
myDDL[0].selectedIndex = 0;
});
I'm new to JQuery and I noticed this line $('#DivID [type=checkbox]') and I was wondering if I can also find the select or option tags using the same method.
Update: I have a div that has more than more tag, I'm trying to get the DropDownList/Select that it's value's just changed.
Update2 I'm using InstaFilta a JQuery plugin that filter the content based on a customized attribute appended to my content tags. Below is a snippet for the function that do the same when working with CheckBoxes, and I'm trying to edit it to work with DropDownLists/Select controls.
var $ex10Checkboxes = $('#ex10 [type=checkbox]');
$ex10Checkboxes.on('change', function() {
var checkedCategories = [];
$ex10Checkboxes.each(function() {
if ($(this).prop('checked')) {
checkedCategories.push($(this).val());
}
});
ex10.filterCategory(checkedCategories, true);
});
You would find the option tags as follows:
$("#DivID option")
Likewise the select tags:
$("#DivID select")
You can then iterate over the returned objects to inspect the individual elements:
var foo = $("#DivID option");
var i;
for (i = 0; i < foo.length; i += 1) {
console.log(foo[i].val()); //or whatever
}
To find the selected element you could check out this question:
$("#DivID option:selected")
I would suggest checking out the JQuery page on Selectors JQuery Selectors
I'm using jQuery to add elements to a specified element. So a user selects options from a drop down menu and it's appended to a div. My jQuery is:
$('#datacombo').on('change', function () {
var selecteddata = $("#datacombo").val().toString();
$('#datadisplay').append("<p>"+ selecteddata + "</p>"); });
my HTML is simple a div:
<div id="datadisplay"></div>
I'm wanting to use ALL the 'selected data' at a later point so i want to add the selected items to a variable array.
I've searched on here and tried these:
How do I gather dropdown values into array with jQuery?
But couldnt get it to work, any suggestions?
Just declare array as global variable. And then push elements to it.
var selectedDatas = new Array();
$('#datacombo').on('change', function () {
var selecteddata = $("#datacombo").val().toString();
selectedDatas.push(selecteddata);
$('#datadisplay').append("<p>"+ selecteddata + "</p>");
});
I have a TableSorted table, and in each TD element are five SPAN elements. Four are always hidden, but upon clicking a div outside the table, certain spans are hidden dependent on which div is clicked.
I have the table sorting fine, but what I need is for the textExtraction to grab a different SPAN, depending on the value of the div which has been selected.
I've tried the following to no avail:
textExtraction:function(node){
var filter=$("div.career a.sel").text();
if(filter=="a"){var theindex=0;}
if(filter=="b"){var theindex=1;}
if(filter=="c"){var theindex=2;}
if(filter=="d"){var theindex=3;}
if(filter=="e"){var theindex=4;}
return $(node).find("span").eq(theindex).text();
}
What is the best way to achieve this?
The textExtraction function is only called when tablesorter is initialized or updated. Try triggering an update after the selection has changed.
var indexes = 'abcde'.split(''),
// Is this a select box?
$sel = $("div.career a.sel").on('change', function(){
$('table').trigger('update');
});
$('table').tablesorter({
textExtraction: function(node){
// if this is a select, get val(), not text()
var filter = $sel.val(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Update: for a link, try this:
var indexes = 'abcde'.split(''),
$careers = $("div.career a").on('click',function(){
var searcher = $(this).attr("rel");
$("div.career a").removeClass("sel");
$(this).addClass("sel");
$("td.stat span").hide();
$("td.stat span.career_" + searcher).show();
});
$('table').tablesorter({
textExtraction: function(node){
// find selected
var filter = $careers.filter('.sel').text(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Note: Don't use live() in jQuery version 1.9+, it was removed.
I want to have on my html-site an combobox like on the following img. I want to get the selected values and print in out. How can I create this comboBox?? I have tried the Google API Visualization CategoryFilter Control. But you can not customize the google control.
Thank you
I just mocked up a combo-box like you described: http://jsfiddle.net/twwGM/
Basically, you need to use JS to capture the onchange event of the select box, and then append its value to some target area with specific styling by generating an HTML string from your function. Keep styles out of the JS and instead style it through the use of a CSS class.
HTML Markup:
<form>
<select id="selector">
<option>Magic</option>
<option>Canaries</option>
<option>Unicorns</option>
</select>
</form>
<div id="target-area"></div>
JS Code
(function () {
document.getElementById("selector").addEventListener("change", function () {
var val = this.options[this.selectedIndex].value;
var genId = val + "-close";
if (!document.getElementById(genId)) {
var htmlstr = "<div class='pasted-option'>" + val + "<span id='" + genId + "'>x</span></div>";
var targetArea = document.getElementById("target-area");
targetArea.innerHTML += htmlstr;
var closeButton = document.getElementById(genId);
closeButton.addEventListener("click", function () {
var parent = this.parentNode;
parent.parentNode.removeChild(parent);
});
}
});
}(window));
As you can see within the code, we also generate an id for the span based on the item's name so that we can make a call to it later for removal from the list. It also gives us the ability to check and make certain the value doesn't already exist within the list.