Populate select dropdown - javascript

I want to populate a select dropdown when the user click in the select. I am trying this, but apparently the click handler is only activated when the user click in the options, but in my case i don't have options. Here is a demo
$('select').click(function () {
var currentId = $(this).attr('id');
alert(currentId);
var total = $('.total').text();
for (i = 0; i <= total; i++) {
$('<option>').val(i).text(i).appendTo('#' + currentId);
}
});

Try this :As you are appending options for every click and hence you are not able to see the options. You can use .one() to populate options only for the first click and for second time click it will show you the populated options. Also use this
to append options instead of getting id of select box and use it.
$('select').one("click",function () {
var total = parseInt($('.total').text());
for (i = 0; i <= total; i++) {
$('<option>').val(i).text(i).appendTo(this);//use this to append
}
});
JSFiddle Demo

You can try to populate the select on mouse over, it could save you some time and give you more accessibility. Sometimes adding options on click just prevents the select from opening when it's supposed to, which can lead to frustrating the user...

Related

Chromium Javascript Snippets. Set select box where the options are populated by a previous select box value

I am using Snippets in the developer tools of a Chromium based web browser (Edge). I am trying to fill out a select box on a form from a website. The issue is that the select box options are dynamically created and are based on a selection from another select box. Every time the 'parent' selection is made the page refreshes and populates the new options for the second select box.
Here is a function that I used to set the first select box, however it doesn't work on the second one. I think it has something to do with when the page refreshes but I am not sure.
//Find value by entered text
function selectElement(selectorType, selector, text) {
var e = document.getElementById(selector);
//find value of text
for (var i = 0; i < e.options.length; i++) {
if (e.options[i].text === text) {
e.selectedIndex = i;
break;
}
}
if (selectorType == "id") {
jqSelector = '#'+selector;
$(jqSelector).val(e.value).change();
}
console.log(jqSelector, e.value);
}
selectElement('id', 'mySelector', "My Text");

Creating Dependent Chechboxradio Buttons - jQuery Mobile

I am trying to create several checkboxradio buttons groups in jQuery mobile that depend on a limit checkboxradio button group value. For example if a limit of 6 is selected I want to only allow the user to be able to select up to a total of 6 children based on all of the other checkboxradio button group selected values and disable everything else. When the limit changes I want to update the UI accordingly.
I have the following code in my change event handler whenever any of the checkboxradio buttons are clicks:
function updateUI(element) {
var limit = parseInt($('input[name="Limit_Total"]:checked').val(), 10);
// Children
var childCount = parseInt($('input[name="Child_Total"]:checked').val(), 10);
var secondChildCount = parseInt($('input[name="Second_Child_Total"]:checked').val(), 10);
var thirdChildCount = parseInt($('input[name="Third_Child_Total"]:checked').val(), 10);
var fourthChildCount = parseInt($('input[name="Fourth_Child_Total"]:checked').val(), 10);
var fifthChildCount = parseInt($('input[name="Fifth_Child_Total"]:checked').val(), 10);
// Totals
var totalChildern = childCount + secondChildCount + thirdChildCount + fourthChildCount + fifthChildCount;
// Enable the correct combination of children
$('input[name*="Child_Total"]').not(element).checkboxradio('disable').checkboxradio('refresh');
for (var i = 0; i <= 6; i++) {
if (i <= (limit - totalChildren)) {
$('input[id$="Child_Total_' + i + '"]').not(element).checkboxradio('enable').checkboxradio('refresh');
} else {
$('input[id$="Child_Total_' + i + '"]').not(element).attr('checked', false).checkboxradio('refresh');
}
}
}
I basically want to simulate the behavior illustrated in the image below:
The problem is it doesn't quite give me the behavior I want. It deselects all but the button I select within the group. I am trying to figure out the most efficient way to do this but I am having a hard time. Any suggestions or help would be greatly appreciated!
I have setup the following jsfiddle to demonstrate the UI: http://jsfiddle.net/X8swt/29/
I managed to solve my problem with the following function:
$('div fieldset').each(function() {
// Disable all none checked inputs
$(this).find('input:not(:checked)').checkboxradio().checkboxradio("disable").checkboxradio("refresh");
// Grab the selected input
var selectedElement = $(this).find('input:checked');
// Calculate the remaining children that can be selected
var remaining = (limit - totalChildern);
// Enable all inputs less than the selected input
$.each($(selectedElement).parent().prevAll().find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
// Enable up to the remaining boxes past the selected input
$.each($(selectedElement).parent().nextAll().slice(0,remaining).find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
});
Please feel free to comment or critique my solution.

Fire a change function without changing focus

I have a table that is sortable and filterable, and everything works fine if I change my filter using a select field. But, if a user doesn't select a filter after x number of seconds, I want it to filter based on a designated option. I have no problem changing the selection after a set time, but the javascript to filter doesn't recognize this is a change() event. How can I get it to recognize it as a change, or by some other way register the default selection after a set period of time?
For reference, I'm using this script for the table filtering/sorting:
http://www.javascripttoolbox.com/lib/table/
I'd like to pass it my own values for Table.filter(this,this).
I think something like this should work:
var defaultFilter = 3;
var filterTimeout = 5000;
window.setTimeout(function() {
var select = document.getElementById("select");
select.selectedIndex = defaultFilter;
Table.filter(select, select);
}, filterTimeout);
HTML:
<select id="select" onchange="Table.filter(this,this)">... </select>
Javascript:
var select = document.getElementById("select");
var secondsToChange = 2;
select.onclick = function() {
window.setTimeout(function(){select.onchange.apply(select)},secondsToChange*1000);
};
I think that should work...

Appending to a select leaks memory JavaScript JQuery

I have a select drop down menu, every time I refresh my page I have to re populate that select drop down. Which is resulting in a memory leak. This is the code any help would be great in refactoring the code. Also I have tried to make another method and calling it before this one, the other method would empty the options array and make it null. That did not help me.
var option = $(document.createElement("option"));
option.attr("value", List.id);
option.text(List.name);
if(List.name.length > maxSize) {
maxSize = List.name.length;
}
this.options.push(option);
//Mark the currently displayed list as the selected option
if (activeListId > 0) {
if (activeListId == List.id) {
option.attr("selected", true);
}
}
}
Toolbar.ListSelect.append(this.options);
It would be very helpful if you included more of the surrounding code so that we could know what is what, but here's my best shot at it given the current situation.
// Reference box
var $box = $('#id-of-select-box');
// Clear select box
$box.empty();
// START LOOP
// Create new option
var $option = $('<option value="'+List.id+'">"'+List.name+'"</option>');
// Append option to select box
$box.append($option);
// END LOOP
//Mark the currently displayed list as the selected option
if (activeListId > 0) {
$box.val(activeListId);
}
I whould suggest to create a new Element, then cut the provided name if exceeds thet maxSize using slice). Later we add the parameter "selected" if there is a match on activeListId and List.id. Latter we append the new option to Toolbar.ListSelect (I suposse it to be the element
var option = jQuery("<option />").attr('value', List.id);
var optionName = List.name.slice(maxSize);
option.text(optionName);
if ( activeListId && activeListId == List.id)
option.attr("selected", true);
option.appendTo(Toolbar.ListSelect)

Convert jQuery script to standalone javascript

Is it possible for this jQuery code to run as a standalone javascript? This is the only javascript I'd like to use in my project so I'd prefer not to load the entire jquery library just for this 1k script.
//chris coyier's little dropdown select-->
$(document).ready(function() {
//build dropdown
$("<select />").appendTo("nav.primary");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("nav select");
// Populate dropdowns with the first menu items
$("div#brdmenu ul li a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav.primary select");
});
//make responsive dropdown menu actually work
$("nav.primary select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
I've tried to find previous answers but most questions are for converting to jquery and not vice-versa :)
It is obviously possible to do those things in straight javascript, but there is no way (that I am aware of) to automatically do that conversion. You will have to go through line by line and do the conversion yourself.
Here is something similar to market's answer. I'm assuming you want to get all the links in UL elements inside the brdmenu element. If you only want the first link on the LI elements, just adjust the loop that gets them.
Also, this is not a good idea. Using select elements for links went out of fashion a long time ago, users much prefer real links. Also, when navigating the options using cursor keys in IE, a change event is dispatched every time a different option is selected so users will only get to select the next option before being whisked away to that location. Much better to add a "Go" button that they press after selecting a location.
The main change is to use an ID to get the nav.primary element, which I assume is a single element that you should be getting by ID already.
function doStuff() {
function getText(el) {
return el.textContent || el.innerText;
}
var div, link, links, uls;
// Use an ID to get the nav.primary element
var navPrimary = document.getElementById('navPrimary');
// Create select element and add listener
var sel = document.createElement('select');
sel.onchange = function() {
if (this.selectedIndex > 0) { // -1 for none selected, 0 is default
window.location = this.value;
}
};
// Create default option and append to select
sel.options[0] = new Option('Go to...','');
sel.options[0].setAttribute('selected','');
// Create options for the links inside #brdmenu
div = document.getElementById('brdmenu');
uls = div.getElementsByTagName('ul');
for (var i=0, iLen=uls.length; i<iLen; i++) {
links = uls[i].getElementsByTagName('a');
for (var j=0, jLen=links.length; j<jLen; j++) {
link = links[j];
sel.appendChild(new Option(getText(link), link.href));
}
}
// Add select to page if found navPrimary element
if (navPrimary) {
navPrimary.appendChild(sel);
}
}
window.onload = doStuff;
It's only 28 lines of actual code, which is only 10 more than the original, doesn't require any supporting library and should work in any browser in use (and most that aren't).
Have a go with this.
The one thing I'm leaving out is $(document).ready, but there are a number of solutions for that available on stackoverflow. It's a surprisingly large amount of code!
But the other functionality:
// build the dropdown
var selectElement = document.createElement('select');
var primary = document.getElementsByClassName('primary')[0];
// create a default option and append it.
var opt = document.createElement('option');
var defaultOpt = opt.cloneNode(false);
defaultOpt.selected = true;
defaultOpt.value = "";
defaultOpt.text = "Go to...";
selectElement.appendChild(defaultOpt);
// populate the dropdown
var brdmenuUl = document.getElementById('brdmenu').getElementsByTagName('ul')[0];
var listItems = brdmenuUl.getElementsByTagName('li');
for(var i=0; i<listItems.length; i++){
var li = listItems[i];
var a = li.getElementsByTagName('a')[0];
var newOpt = opt.cloneNode(false);
newOpt.value = a.href;
newOpt.text = a.innerHTML;
selectElement.appendChild(newOpt);
}
// now listen for changes
if(selectElement.addEventListener){
selectElement.addEventListener('change', selectJump, false);
}
else if(selectElement.attachEvent){
selectElement.attachEvent('change', selectJump);
}
function selectJump(evt){
window.location = evt.value;
}
primary.appendChild(selectElement);​
some notes!
We're not looking specifically for nav.primary, we're just finding the first occurrence of something with class .primary. For best performance, you should add an ID to that element and use getElementById instead.
Similarly with the lists in #brdmenu, we look for the first UL, and the first A inside each LI. This isn't exactly what the jQuery does, if you are going to need to iterate more than one UL inside #brdmenu you can use another for loop.
I think that should all work though, there's a fiddle here

Categories