How to select the first element in select box a, if I am at last position. if I am in middle of the list I am able to select but not able to select the first item in list if my current position is last.
function MoveSelected(objSourceElement, objTargetElement)
{
var aryTempSourceOptions = new Array();
var x = 0;
var y = 0;
//looping through source element to find selected options
for (var i = 0; i < objSourceElement.length; i++) {
if (objSourceElement.options[i].selected) {
y++;
//need to move this option to target element
var intTargetLen = objTargetElement.length++;
objTargetElement.options[intTargetLen].text = objSourceElement.options[i].text;
objTargetElement.options[intTargetLen].value = objSourceElement.options[i].value;
}
else {
//storing options that stay to recreate select element
var objTempValues = new Object();
objTempValues.text = objSourceElement.options[i].text;
objTempValues.value = objSourceElement.options[i].value;
aryTempSourceOptions[x] = objTempValues;
x++;
}
}
if (y==0) alert("Please select any Course");
//resetting length of source
objSourceElement.length = aryTempSourceOptions.length;
//looping through temp array to recreate source select element
for (var i = 0; i < aryTempSourceOptions.length; i++) {
objSourceElement.options[i].text = aryTempSourceOptions[i].text;
objSourceElement.options[i].value = aryTempSourceOptions[i].value;
//objSourceElement.options[i].selected = false;
}
}
I'm late to this party but I have code that swaps selected values between two containers, taking care to keep track of option groups if they exist:
function MoveSelectedItems(source, destination)
{
var sourceElement = document.getElementById(source);
var destinationElement = document.getElementById(destination);
var toSource = {};
var toDestination = {};
// Move all children from our destination element into our toDestination
// dicationary. This will be used to make sure groups are properly populated
// between source and destination
while (destinationElement.firstChild)
{
var child = destinationElement.firstChild;
destinationElement.removeChild(child);
toDestination[child.label] = child;
}
// Loop through all the children of our source and move them to toDestination if
// they're selected and to toSource if not. Also creates options groups as necessary
while (sourceElement.firstChild)
{
var outerChild = sourceElement.firstChild;
sourceElement.removeChild(outerChild)
// If the current outerChild is an option group...
if (outerChild.nodeName == 'OPTGROUP')
{
// Loop through the children of the current option group outer child
while (outerChild.firstChild)
{
var innerChild = outerChild.firstChild;
outerChild.removeChild(innerChild);
// If the child of the option group is selected...
if (innerChild.selected == true)
{
// If the option group isn't already in the destination dictionary
// add it using the label of the outer child as the key
if (!(outerChild.label in toDestination))
{
toDestination[outerChild.label] = document.createElement('optgroup');
toDestination[outerChild.label].label = outerChild.label;
}
innerChild.selected = false;
// Add the inner child to it's parent group in the destination dictionary
toDestination[outerChild.label].appendChild(innerChild);
}
else // If the child of the option group isn't selected...
{
// If the option group isn't already in the source ditionary
// add it using the label of the outer child as the key
if (!(outerChild.label in toSource))
{
toSource[outerChild.label] = document.createElement('optgroup');
toSource[outerChild.label].label = outerChild.label;
}
innerChild.selected = false;
// Add the inner child to it's parent group in the source dictionary
toSource[outerChild.label].appendChild(innerChild);
}
}
}
else if (outerChild.nodeName == 'OPTION') // If the outer child is an option...
{
// If the outer child is selected, add it to the destination
// dictionary using its label as the key.
// Otherwise, if the the outer child is not selected, add it to
// the source dictionary using it's label as the key.
if (outerChild.selected == true)
{
outerChild.selected = false;
toDestination[outerChild.label] = outerChild;
}
else
{
toSource[outerChild.label] = outerChild;
}
}
}
// Loop through the elements in toSource, sort them and append them to
// the Source element
for (var i in toSource)
{
sourceElement.appendChild(toSource[i]);
}
// Loop through the elements in toDestination, sort them and append them to
// the Destination element
for (var i in toDestination)
{
destinationElement.appendChild(toDestination[i]);
}
}
Java Script Function :
function listbox_move(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if (-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if (direction == 'up')
increment = -1;
else
increment = 1; if ((selIndex + increment) < 0 || (selIndex + increment) > (listbox.options.length - 1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;
}
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for (var count = 0; count < src.options.length; count++) {
if (src.options[count].selected == true) {
var option = src.options[count];
var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null);
src.remove(count, null);
} catch (error) {
dest.add(newOption);
src.remove(count);
}
count--;
}
}
}
function listbox_selectall(listID, isSelect) {
var listbox = document.getElementById(listID);
for (var count = 0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
}
HTML Code :
<table>
<tr valign="top">
<td>
<SELECT id="s" size="10" multiple>
<OPTION value="a">Afghanistan</OPTION>
<OPTION value="b">Bahamas</OPTION>
<OPTION value="c">Barbados</OPTION>
<OPTION value="d">Belgium</OPTION>
<OPTION value="e">Bhutan</OPTION>
<OPTION value="f">China</OPTION>
<OPTION value="g">Croatia</OPTION>
<OPTION value="h">Denmark</OPTION>
<OPTION value="i">France</OPTION>
</SELECT>
</td>
<td valign="center">
>>
<br/>
<<
</td>
<td>
<SELECT id="d" size="10" multiple>
<OPTION value="a">Afghanistan</OPTION>
<OPTION value="b">Bahamas</OPTION>
<OPTION value="c">Barbados</OPTION>
<OPTION value="d">Belgium</OPTION>
<OPTION value="e">Bhutan</OPTION>
<OPTION value="f">China</OPTION>
<OPTION value="g">Croatia</OPTION>
<OPTION value="h">Denmark</OPTION>
<OPTION value="i">France</OPTION>
</SELECT>
</td>
</tr>
</table>
Related
On a button click, I want to run a function that will each time randomly select an option from a select dropdown that wasn't chosen before. And if all options were chosen, I want to reset the used options and start from the beginning.
I have a function that chooses an element that wasn't chosen before randomly from an array (credit to #Rajesh)
function randomize(arr) {
let data = [...arr];
let chosenItems = [];
function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];
chosenItems.push(choice);
return choice;
}
return {
randomItem: getRandomValue
}
}
const dummyData = [ 1,2,3,4,5 ];
const randomizeData = randomize(dummyData);
for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}
I have already created a script that randomly chooses an element from a select2 dropdown but it selects the same element very often.
var optionsArray = new Array();
var first = $('select option')[0];
$('select option').each(function () { optionsArray.push(this) });
if (optionsArray.length > 1) {
$('select').html('');
var i = 0;
var random
while (i < optionsArray.length) {
random = Math.floor(Math.random() * optionsArray.length)
//if element hasn't been marked as "selected"
if (optionsArray[random] != "selected") {
$("select").append(optionsArray[random]);
//mark element as selected
optionsArray[random] = "selected"
i++
}
}
var newSelectedOption = $('select option')[0];
$('select').val($(newSelectedOption).val()).trigger('change');
<html>
<body>
<select id="dropdown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="btn">
Generate
</button>
</body>
<script>
let dropdown = document.getElementById('dropdown');
var options = [];
var chosenItems = [];
function setOptions(){
for(var i = 0; i < dropdown.options.length; i++)
options.push(dropdown.options[i].value);
}
document.getElementById('btn').addEventListener("click", function(){
options = options.filter( function( el ) {
return chosenItems.indexOf( el ) < 0;
});
if(options.length == 0){
console.log("reset data")
setOptions();
chosenItems = [];
}
var unSelectedRandom = options[Math.floor(Math.random() * options.length)]
for(var i = 0; i < dropdown.options.length; i++){
var current = dropdown.options[i]
if ( current.value == unSelectedRandom ) {
dropdown.selectedIndex = i;
chosenItems.push(current.value);
console.log("chosen: "+chosenItems)
}
}
});
</script>
</html>
I have a select tag of dynamically added elements. I need to add an event listener to each of the elements in the select tag except the first which:
adds the text of the element to a list,
makes the focus of the list the first element again, and
removes or hides the clicked element.
The first element is a 'none' element which doesn't need any event listener.
I've tried something like
for (var i = 0; i < array.length; i++)
{
var name = array[i];
var selectElement = document.getElementById(selectElementId);
addToSelectNode(document.getElementById(selectElementId), name);
var thisNode = selectElement.childNodes[i];
if (thisNode.value != "none")
{
thisNode.addEventListener("click", function(event)
{
appendNodeToList("artist-list", i);
selectElement.selectedIndex = 0;
selectElement.remove(selectElement.i);
selectElement.style.display = "none";
});
}
}
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}
function appendNodeToList(listId, text)
{
var newNode = document.createElement("LI");
var textNode = document.createTextNode(text);
newNode.appendChild(textNode);
document.getElementById(listId).appendChild(newNode);
}
Didn't work at all though
A few hours later I've solved my own question. The problem stemmed from trying to remove items in the select tag which just wasn't working - I'm nut sure if it's possible but making it disabled solved it. Anyway here's the result.
HTML:
<select id="artist-select-list">
<option value="none">none</option>
</select>
JavaScript:
window.onload = function()
{
var dropdown = document.getElementById("sampleDropdown");
var n = array.length;
// Loop to add to <select> dropdown
for (var i = 1; i <= n; i++)
{
addToSelectNode(dropdown, array[i - 1]);
}
// Loop to add id's to each element in the dropdown
for (var i = 0; i <= n; i++)
{
dropdown[i].id = "selectNum" + i;
}
// Loop to add event listener
for (var i = 0; i < dropdown.length; i++)
{
dropdown[i].addEventListener("click", function(event)
{
// Regardless of which option the user clicks move shown option to "none" (first index in dropdown)
dropdown.selectedIndex = 0;
if (event.target.id != "selectNum0")
{
// Disable once clicked
event.target.disabled = true;
// Do other things here in relation to event.target
}
});
}
}
var array =
[
"sampleText1", "sampleText2"
];
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}
I need to change the contents of dropdown B based on the selection in dropdown A using javascript. There are no db queries involved--I know beforehand what the contents of B should be given the choice in A. I have found some examples using AJAX, but since there is no db query involved that's not necessary. Can anyone point me to some example code for how to do this?
function configureDropDownLists(ddl1, ddl2) {
var colours = ['Black', 'White', 'Blue'];
var shapes = ['Square', 'Circle', 'Triangle'];
var names = ['John', 'David', 'Sarah'];
switch (ddl1.value) {
case 'Colours':
ddl2.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(ddl2, colours[i], colours[i]);
}
break;
case 'Shapes':
ddl2.options.length = 0;
for (i = 0; i < shapes.length; i++) {
createOption(ddl2, shapes[i], shapes[i]);
}
break;
case 'Names':
ddl2.options.length = 0;
for (i = 0; i < names.length; i++) {
createOption(ddl2, names[i], names[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>
<select id="ddl2">
</select>
Setup mine within a closure and with straight JavaScript, explanation provided in comments
(function() {
//setup an object fully of arrays
//alternativly it could be something like
//{"yes":[{value:sweet, text:Sweet}.....]}
//so you could set the label of the option tag something different than the name
var bOptions = {
"yes": ["sweet", "wohoo", "yay"],
"no": ["you suck!", "common son"]
};
var A = document.getElementById('A');
var B = document.getElementById('B');
//on change is a good event for this because you are guarenteed the value is different
A.onchange = function() {
//clear out B
B.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for (var i in bOptions[_val]) {
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
B.appendChild(op);
}
};
//fire this to update B on load
A.onchange();
})();
<select id='A' name='A'>
<option value='yes' selected='selected'>yes
<option value='no'> no
</select>
<select id='B' name='B'>
</select>
Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice
Hi I am struggling with doing this in raw JavaScript. Currently I have two dropdowns a parent and a child like so:
<select id="state" title="" name="state">
<option selected="selected" value="Open" label="Open">Open</option>
<option value="Closed" label="Closed">Closed</option>
</select>
<select id="status" title="" name="status">
<option value="Open_New" label="New">New</option>
<option value="Open_Assigned" label="Assigned">Assigned</option>
<option value="Closed_Closed" label="Closed">Closed</option>
<option value="Open_Pending Input" label="Pending External Input">Pending External Input</option>
<option value="Open_Pending" label="Pending Internal Input">Pending Internal Input</option>
<option value="Closed_Duplicate" label="Duplicate">Duplicate</option>
<option value="Open_CARD" label="CARD">CARD</option>
<option value="Open_Open" label="Open">Open</option>
<option value="Open_DAD" label="DAD">DAD</option>
<option value="Closed_Rejected" label="Rejected">Rejected</option>
</select>
And the child dropdown values are selected based on the parent dropdown values name with and an underscore:
function updateDynamicEnum(field, subfield){
if(document.getElementById(subfield) != null){
var selector = document.getElementById(subfield);
var de_key = document.getElementById(field).value;
var current = [];
for (var i = 0; i < selector.length; i++) {
if (selector.options[i].selected) current.push(selector.options[i].value);
}
if(de_entries[subfield] == null){
de_entries[subfield] = new Array;
for (var i=0; i<selector.options.length; i++){
de_entries[subfield][selector.options[i].value] = selector.options[i].text;
}
}
document.getElementById(subfield).innerHTML = '';
for (var key in de_entries[subfield]) {
if(key.indexOf(de_key+'_') == 0){
selector.options[selector.options.length] = new Option(de_entries[subfield][key], key);
}
}
for (var key in current) {
for (var i = 0; i < selector.length; i++) {
if(selector.options[i].value == current[key])
selector[i].selected = true;
}
}
}
What I need to do is change this code so that child dropdown values are not selected based on the key name with an underscore but selected when they are part of an array that is passed in. The array is called child_strings and looks like this:
'open' => array(
'Open_New',
'Open_Assigned',
'Open_Pending Input',
'Open_Pending',
'Open_CARD',
'Open_Open',
'Open_DAD'
),
'closed' => array(
'Open_Assigned',
'Closed_Closed',
'Closed_Duplicate',
'Closed_Rejected',
),
my new code looks like this:
function updateDynamicEnum(field, subfield, child_strings){
//console.log(child_strings);
if(document.getElementById(subfield) != null){
var de_key = document.getElementById(field).value;
var child = document.getElementById(subfield);
var current = [];
for (var i = 0; i < child.length; i++) {
if (child.options[i].selected) current.push(child.options[i].value);
}
if(de_entries[subfield] == null){
de_entries[subfield] = new Array;
for (var i=0; i<child.options.length; i++){
de_entries[subfield][child.options[i].value] = child.options[i].text;
}
}
document.getElementById(subfield).innerHTML = '';
//this part needs changes
for (var key in de_entries[subfield]) {
if(key.indexOf(de_key+'_') == 0){
child.options[child.options.length] = new Option(de_entries[subfield][key], key);
}
}
But struggling to see how to check child_strings and determine if the vales is in that array etc..
I figured the answer out for myself but if somebody can post a better one please go ahead.
function updateDynamicEnum(field, subfield, child_strings){
if(document.getElementById(subfield) != null){
var de_key = document.getElementById(field).value;
var child = document.getElementById(subfield);
var current = [];
for (var i = 0; i < child.length; i++) {
if (child.options[i].selected) current.push(child.options[i].value);
}
if(de_entries[subfield] == null){
de_entries[subfield] = new Array;
for (var i=0; i<child.options.length; i++){
de_entries[subfield][child.options[i].value] = child.options[i].text;
}
}
document.getElementById(subfield).innerHTML = '';
var arg = child_strings[de_key];
for (var key in de_entries[subfield]) {
if(isInArray(key,arg)){
child.options[child.options.length] = new Option(de_entries[subfield][key], key);
}
}
for (var key in current) {
for (var i = 0; i < child.length; i++) {
if(child.options[i].value == current[key])
child[i].selected = true;
}
}
}
/*Checks if value is in an array*/
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
}
I have select
<select multiple id="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
And two buttons
<input type="button" value="Up" onclick="up()">
<input type="button" value="Down" onclick="down()">
How can I move selected option in multiselect up and down by buttons using jquery?
Update: Fixed code for multiple options selected, based on #patrick dw's suggestion.
$(document).ready(function(){
$('input[type="button"]').click(function(){
var $op = $('#select2 option:selected'),
$this = $(this);
if($op.length){
($this.val() == 'Up') ?
$op.first().prev().before($op) :
$op.last().next().after($op);
}
});
});
Test it here ยป
No need to use inline onclick="" event listeners. jQuery takes full control of separating presentation from functionality.
if you do not use jquery
function moveUp(){
var select = document.getElementById("columnOrder");
var options = select && select.options;
var selected = [];
for (var i = 0, iLen = options.length; i < iLen; i++) {
if (options[i].selected) {
selected.push(options[i]);
}
}
for (i = 0, iLen = selected.length; i < iLen; i++) {
var index = selected[i].index;
if(index == 0){
break;
}
var temp = selected[i].text;
selected[i].text = options[index - 1].text;
options[index - 1].text = temp;
temp = selected[i].value;
selected[i].value = options[index - 1].value;
options[index - 1].value = temp;
selected[i].selected = false;
options[index - 1].selected = true;
}
}
function moveDown(){
var select = document.getElementById("columnOrder");
var options = select && select.options;
var selected = [];
for (var i = 0, iLen = options.length; i < iLen; i++) {
if (options[i].selected) {
selected.push(options[i]);
}
}
for (i = selected.length - 1, iLen = 0; i >= iLen; i--) {
var index = selected[i].index;
if(index == (options.length - 1)){
break;
}
var temp = selected[i].text;
selected[i].text = options[index + 1].text;
options[index + 1].text = temp;
temp = selected[i].value;
selected[i].value = options[index + 1].value;
options[index + 1].value = temp;
selected[i].selected = false;
options[index + 1].selected = true;
}
}
function up() {
var selected = $("#select2").find(":selected");
var before = selected.prev();
if (before.length > 0)
selected.detach().insertBefore(before);
}
function down() {
var selected = $("#select2").find(":selected");
var next = selected.next();
if (next.length > 0)
selected.detach().insertAfter(next);
}
I created a jquery plugin for this:
https://github.com/UziTech/jquery.moveSelected.js
usage:
$("button#up").click(function(){
$("select").moveSelectedUp();
});
$("button#down").click(function(){
$("select").moveSelectedDown();
});
http://jsfiddle.net/UziTech/qr5qfhgg/
here is the same idea as the previously-posted non-jquery example, but with some strategic code re-use. My need was to have the buttons always operate on the same select element, named "cols". You could put "sel" as a parameter of the moveUp() and moveDown() functions if you want something more generic.
function moveUp() {
var sel = document.getElementById("cols");
var i1=0, i2=1;
while (i2 < sel.options.length) {
swapIf(sel,i1++,i2++);
}
}
function moveDown() {
var sel = document.getElementById("cols");
var i1=sel.options.length-1, i2=i1-1;
while (i1 > 0) {
swapIf(sel,i1--,i2--);
}
}
var swapVar = '';
function swapIf(sel,i1,i2) {
if ( ! sel[i1].selected && sel[i2].selected) {
swapVar = sel[i2].text;
sel[i2].text = sel[i1].text;
sel[i1].text = swapVar;
swapVar = sel[i2].value;
sel[i2].value = sel[i1].value;
sel[i1].value = swapVar;
sel[i1].selected = true;
sel[i2].selected = false;
}
}
In case you have a optgroup in the select element this will also move it to the next /prev optgroup:
function up() {
var selected = $("#target-select").find(":selected");
var before = selected.prev();
if (before.length > 0){
selected.detach().insertBefore(before);
} else {
selected.parent().prev('optgroup').append(selected)
}
}
function down() {
var selected = $("#target-select").find(":selected");
var next = selected.next();
if (next.length > 0){
selected.detach().insertAfter(next);
} else {
selected.parent().next('optgroup').prepend(selected)
}
}
<script type="text/javascript">
$(document).ready(function() {
$('li').click(function() {
// the clicked LI
var clicked = $(this);
// all the LIs above the clicked one
var previousAll = clicked.prevAll();
// only proceed if it's not already on top (no previous siblings)
if(previousAll.length > 0) {
// top LI
var top = $(previousAll[previousAll.length - 1]);
// immediately previous LI
var previous = $(previousAll[0]);
// how far up do we need to move the clicked LI?
var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
// how far down do we need to move the previous siblings?
var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
// let's move stuff
clicked.css('position', 'relative');
previousAll.css('position', 'relative');
clicked.animate({'top': -moveUp});
previousAll.animate({'top': moveDown}, {complete: function() {
// rearrange the DOM and restore positioning when we're done moving
clicked.parent().prepend(clicked);
clicked.css({'position': 'static', 'top': 0});
previousAll.css({'position': 'static', 'top': 0});
}});
}
});
});
</script>
<ul>
<li><a>Hank</a></li>
<li><a>Alice</a></li>
<li><a>Tom</a></li>
<li><a>Ashlee</a></li>
</ul>