Select list to associated array - javascript

I have a select with options and values:
<select id="sid">
<option value="sValue1">sText1</option>
...
</select>
I need to create an associated array for all pairs:
var data = {"sText1":"sValue1",...};
Is there ready/simplifies tools to do that?

It's a basic for ... on ... iteration.
Take note that if there are multiple <option> with the same label, the last one will take place in the result object.
const select = document.getElementById('sid');
const objContainer = document.getElementById('sid-obj');
const options = select.getElementsByTagName('option');
const selectObj = {};
for (const opt of options) {
let optObj = {};
optObj[opt.textContent] = opt.value;
Object.assign(selectObj, optObj);
}
// print result in code
objContainer.textContent = JSON.stringify(selectObj);
<select id="sid">
<option value="">Default</option>
<option value="sValue1">sText1</option>
<option value="sValue2">sText2</option>
<option value="sValue3">sText3</option>
<option value="sValue4">sText4</option>
<option value="sValue5">sText4</option>
</select>
<h2>Result:</h2>
<code id="sid-obj" />

Add a function to the select which will be called on change and on change get the value and the text from the selected option
function getValue(elem) {
let obj = {};
obj[elem.options[elem.selectedIndex].text] = elem.value
console.log(obj)
}
<select id="sid" onchange='getValue(this)'>
<option value="sValue1">sText1</option>
<option value="sValue2">sText2</option>
<option value="sValue3">sText3</option>
</select>

Sorry for being late to the party but here is a jQuery solution for the same.
var arr = {};
$("#sid option").each(function() {
let text = $(this).text();
arr[text] = $(this).val();
});
// print result
$('#sid-obj').append(JSON.stringify(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sid">
<option value="">Default</option>
<option value="sValue1">sText1</option>
<option value="sValue2">sText2</option>
<option value="sValue3">sText3</option>
<option value="sValue4">sText4</option>
<option value="sValue5">sText4</option>
</select>
<h2>Result:</h2>
<code id="sid-obj" />

Related

javascript select alphabetically sorting

I am trying to sort option alphabetically
My Html is
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
js
var options = $("#myOpt option");
options.detach().sort(function(a,b) {
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0);
});
options.appendTo("#myOpt");
it sorts option correctly but now instead of selected option it shows last option. My question is how to show selected option instead of last option and can it be done by another client side method? since for big list it making page slow
Try this,
var options = $("#myOpt option");
var selectedVal = '';
options.detach().sort(function(a,b) {
var at = $(a).text();
var bt = $(b).text();
if($(a).attr('selected') || $(b).attr('selected')){
selectedVal = $(a).attr('selected') ? $(a).val() : $(b).val();
return false;
}
return (at > bt)?1:((at < bt)?-1:0);
});
options.appendTo("#myOpt");
$('#myOpt').val(selectedVal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
Don't select the 1st option to sort. var options = $("#myOpt option:not(:eq(0))");
You may use web workers to avoid browser frize if this a big list.
also, you can put it inside setTimeout to push it in event loop
$(function() {
var options = $("#myOpt option:not(:eq(0))");
options.detach().sort(function(a, b) {
var be = $(b);
var ae = $(a);
if (be.attr('selected')) {
selectedVal = be.val();
return 1;
}
if (ae.attr('selected')) {
selectedVal = ae.val();
return -1;
}
var at = ae.text();
var bt = be.text();
return (at > bt) ? 1 : ((at < bt) ? -1 : 0);
});
options.appendTo("#myOpt");
$("#myOpt").val(selectedVal);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
$(function() {
var options = $("#myOpt option");
options.detach().sort(function(a, b) {
var be = $(b);
var ae = $(a);
if (be.attr('selected')) {
selectedVal = be.val();
return 1;
}
if (ae.attr('selected')) {
selectedVal = ae.val();
return -1;
}
var at = ae.text();
var bt = be.text();
return (at > bt) ? 1 : ((at < bt) ? -1 : 0);
});
options.appendTo("#myOpt");
$("#myOpt").val(selectedVal);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
To do the sort using native JavaScript may actually give you somewhat more readable code, while taking advantage of operations (like shift/unshift) that jQuery does not implement.
The selection issue is occurring because an option detached from it's parent select cannot be selected - so you need to either select the first option again.
document.addEventListener("DOMContentLoaded", function() {
var options = $("#myOpt option").detach()
options = $.makeArray(options);
var first = options.shift();
options.sort( (a,b) => a.text.localeCompare(b.text) );
options.unshift(first);
$("#myOpt").append(options);
$("#myOpt option").eq(0).prop("selected", true)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
You may want to simply just leave the selected element alone and just detach/sort the others, which ends up being quite a bit simpler:
document.addEventListener("DOMContentLoaded", function() {
var options = $("#myOpt option").not('[value=""]').detach();
options.sort( (a,b) => a.text.localeCompare(b.text) );
$("#myOpt").append(options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>

HTML5 Select Multiple Values to Array

We would like to use HTML5 select input to return an array of values, for example this select input
<select id="fruits" multiple>
<option value="oranges">Oranges</option>
<option value="apples" selected>Apples</option>
<option value="grapes" selected>Grapes</option>
</select>
When we are trying to get the value using
fruits = fruits.value // this produces only 'apples'
Why Only Apples? How can we get the value from the select input to return an array of fruits (values) ?
Thanks!
btw - this can be seen in the following fiddle :
https://jsfiddle.net/eaby035z/
Also, How can we do this the other way around?!
var favorites = ['apples','oranges'];
fruits.value = favorites // doesn't work...
One possible solution would be :
At first you need to select all the options and iterate through them.
options would be a HTMLCollection and you can iterate using a for loop ( among others ) and inside that for loop you can get the values. See below
TO get them inside an array just push them in an empty array.
const select = document.getElementById("select")
const options = select.options
const fruits = [];
for ( let i=0; i< options.length; i++) {
fruits.push(options[i].value)
}
console.log(fruits)
<select id="select" multiple>
<option value="oranges">Oranges</option>
<option value="apples" selected>Apples</option>
<option value="grapes" selected>Grapes</option>
</select>
One other solution would be to use map array method on the options HTML collection. map returns an array. ( just like haim770 mentioned in the comment to your question )
const select = document.getElementById("select")
const options = select.options
fruitArray = Array.prototype.map.call(options, option => option.value )
console.log(fruitArray)
<select id="select" multiple>
<option value="oranges">Oranges</option>
<option value="apples" selected>Apples</option>
<option value="grapes" selected>Grapes</option>
</select>
After your EDIT to the question asking how to set some values to the options
const favorites = ['value1','value2', 'value3'];
const select = document.getElementById("select")
const options = select.options
for ( let i=0; i< options.length; i++) {
options[i].value = favorites[i]
options[i].innerText = favorites[i]
}
<select id="select" multiple>
<option value="oranges">Oranges</option>
<option value="apples" selected>Apples</option>
<option value="grapes" selected>Grapes</option>
</select>
you can easily do it using JQUERY. Hope it will Help
var selectedOptions = $("#select").val();
console.log(selectedOptions);
function onSelectChange(){
var selectedOptions = $("#select").val();
console.log(selectedOptions);
}
var setValue = ["apples","mango"];
function setOptions(){
$("#select option").prop("selected", false);
for(var i=0;i<setValue.length;i++){
$("#select option[value='" + setValue[i] + "']").prop("selected", true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select" multiple onChange="onSelectChange()">
<option value="oranges">Oranges</option>
<option value="apples" selected>Apples</option>
<option value="grapes" selected>Grapes</option>
<option value="mango" >mango</option>
</select>
<button onClick="setOptions()" >Set Programatically</button>
Iterate through the options of select and get all the option where selected is true.
const select = document.getElementById("select")
const options = select.options
const fruits = [];
for (let i = 0; i < options.length; i++) {
if (options[i].selected == true) {
console.log(options[i].value)
}
}
<select id="select" multiple>
<option value="oranges">Oranges</option>
<option value="apples" selected>Apples</option>
<option value="grapes" selected>Grapes</option>
</select>

Form input values to JSON

The Issue
I am trying to convert form inputs to a json object but having difficulty trying to achieve this, below is a snippet of the HTML which I have and the JSON which I'm trying to get.
{
"2019-01-23": [
{
id: 1,
period: 'am'
},
{
id: 2,
period: 'pm'
}
]
}
<select name="dates[2019-01-23][0][id]">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="dates[2019-01-23][0][period]">
<option selected>am</option>
<option>pm</option>
</select>
<select name="dates[2019-01-23][1][id]">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>
<select name="dates[2019-01-23][1][period]">
<option>am</option>
<option selected>pm</option>
</select>
What I've tried
var inputs = $(':input').serializeArray();
var json = [];
$.each(inputs, function(key, input) {
var names = input.name.split(/\[(.*?)\]/);
var data = [];
data[names[1]] = [];
data[names[1]][names[3]] = { id: null, period: null };
if(names[5] == 'id') {
data[names[1]][names[3]].id = input.value;
}
if(names[5] == 'period') {
data[names[1]][names[3]].period = input.value;
}
json.push(data);
});
But this doesn't quite achieve what I'm after (multiple of the same date) and I'm getting a bit lost now, I'm sure there must be a way of doing this a lot easier.
First, match is more appropriate for your case than split.
Furthermore, since json is object literal, it should be initialised with empty object ({}), not array.
push is not quite appropriate for your case. It's better to use direct assignment instead.
So the code might look like this:
var inputs = $(':input').serializeArray();
var json = {};
$.each(inputs, function(key, input) {
var keys = input.name.match(/([^\[\]]+)/g).slice(1);
var date = keys[0], i = keys[1], id = keys[2];
if (!json[date]) json[date] = [];
if (!json[date][i]) json[date][i] = {};
json[date][i][id] = input.value;
});
console.log(JSON.stringify(json));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<select name="dates[2019-01-23][0][id]">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="dates[2019-01-23][0][period]">
<option selected>am</option>
<option>pm</option>
</select>
<select name="dates[2019-01-23][1][id]">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>
<select name="dates[2019-01-23][1][period]">
<option>am</option>
<option selected>pm</option>
</select>

How to store value from one dropdown list to another dropdown list

I have 2 dropdown list, where in the first dropdown list i have some data and if I select the data it has to be stored into the second dropdown list. Here is the code :-
This is the first dropdown list,
<select name="weekId" id="weekId" onchange="getSelected(value)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
This is the second list,
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
If I select Weekly in the first dropdown, the value has to get stored in the second dropdown. How do I go about implementing this?
Thanks in advance!!
var weekId = document.getElementById('weekId')
, selectedWeek = document.getElementById('selectedWeek')
, option;
weekId.onchange = function() {
option = document.createElement('option');
option.value = this.value;
option.text = this.options[this.selectedIndex].text;
selectedWeek.appendChild(option);
weekId.removeChild(this.options[this.selectedIndex]);
};​
see working fiddle here: http://jsfiddle.net/bKrFK/1/
the last line in the event-handler will remove the selected option from the weekId select-box (remove that line if not needed)
You can do this using Javascript:
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); //Standard
src.remove(count, null);
}catch(error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
}
Pass this function with ids of your selectbox.
For Demo: Listbox move left-right options JavaScript
Try this..
<html>
<body>
<select name="weekId" id="weekId" onchange="document.getElementById('selectedWeek').value=this.value">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
</body>
</html>
Note : Second drop down has all value available in first select box.
First of all, when you call the javascript function in onChange event, replace getSelected(value) to getSelected(this.value).
Now after that,
Your javascript function getSelected(value) should look like this
function getSelected(value)
{
document.getElementById("selectedWeek").innerHTML = '<option value="'+value+'">'+value+'</option>';
}
You could use the following, without any jQuery dependencies.
I've added some comments to explain what is going on.
<script>
function handleSelection(weekDropDown) {
// Get selected value
var selection = weekDropDown.options[weekDropDown.selectedIndex].value;
var selectedWeekDropDown = document.getElementById("selectedWeek");
var opt;
if(selectedWeekDropDown.options[0]) {
// Replace
opt = selectedWeekDropDown.options[0];
} else {
// Add an option
opt = document.createElement("option");
}
if(!selectedWeekDropDown.options[0]) {
selectedWeekDropDown.options.add(opt);
}
// Set the option text and value
opt.text = selection;
opt.value = selection;
}
</script>
<select name="weekId" id="weekId" onchange="handleSelection(this)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">

Changing the selected option of an HTML Select element

In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';​​​​​​​​​​
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})

Categories

Resources