Issue changing value of dropdown with js [duplicate] - javascript

I want to create a function in order to programmatically add some elements on a page.
Lets say I want to add a drop-down list with four options:
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
How can I do that?

This will work (pure JS, appending to a div of id myDiv):
Demo: http://jsfiddle.net/4pwvg/
var myParent = document.body;
//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}

var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
var cars = [
"volvo",
"saab",
"mercedes",
"audi"
];
var options_str = "";
cars.forEach( function(car) {
options_str += '<option value="' + car + '">' + car + '</option>';
});
sel.innerHTML = options_str;
window.onload = function() {
document.body.appendChild(sel);
};

I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
Pure Javascript Create Element Solution
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
JSFiddle Demo
This can be highly customized to suit your project!

This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.
var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];
var sEle = document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);
for (var i = 0; i < array.length; ++i) {
var oEle = document.createElement('option');
if (i == 0) {
oEle.setAttribute('disabled', 'disabled');
oEle.setAttribute('selected', 'selected');
} // end of if loop
var oTxt = document.createTextNode(array[i]);
oEle.appendChild(oTxt);
document.getElementsByTagName('select')[0].appendChild(oEle);
} // end of for loop

Here's an ES6 version of the answer provided by 7stud.
const sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
const cars = [
"Volvo",
"Saab",
"Mercedes",
"Audi",
];
const options = cars.map(car => {
const value = car.toLowerCase();
return `<option value="${value}">${car}</option>`;
});
sel.innerHTML = options;
window.onload = () => document.body.appendChild(sel);

const countryResolver = (data = [{}]) => {
const countrySelecter = document.createElement('select');
countrySelecter.className = `custom-select`;
countrySelecter.id = `countrySelect`;
countrySelecter.setAttribute("aria-label", "Example select with button addon");
let opt = document.createElement("option");
opt.text = "Select language";
opt.disabled = true;
countrySelecter.add(opt, null);
let i = 0;
for (let item of data) {
let opt = document.createElement("option");
opt.value = item.Id;
opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
countrySelecter.add(opt, null);
}
return countrySelecter;
};

Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:
function select(options, selected) {
return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);
}
$('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];
let domSelect = document.createElement('select');
domSelect.multiple = true;
document.getElementsByTagName('body')[0].appendChild(domSelect);
for (const i in cars) {
let optionSelect = document.createElement('option');
let optText = document.createTextNode(cars[i]);
optionSelect.appendChild(optText);
document.getElementsByTagName('select')[0].appendChild(optionSelect);
}

it's very simple yet tricky but here is what you wanted, hope it's helpful :
this function generates a select list from 1990 to 2018
i think this example can help ya, if you want to add any other value just
change value of x and y ;)
function dropDown(){
var start = 1990;
var today = 2019;
document.write("<select>");
for (var i = start ; i <= today; i++)
document.write("<option>" + i + "</option>");
}
document.write("</select>");
dropDown();

Related

Get selected option's value in Javascript

I am using Javascript in back-end (Odoo, it's Python web framework) and i want to get selected option to save object.
i have consider event like this
events: {
'click .GenderClass': 'clickPill',
},
and then i have code where i build selected option to show in page
_renderEdit: function () {
this.$el.empty();
var array = ['', 'Male', 'Female'];
var selectList = document.createElement("select");
selectList.className = "GenderClass";
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);}
this.$el.append(selectList);
},
and when user click Male or Female i want to call clickPill and it's working but when i want to get selected option value then it's undefined
clickPill: function (ev) {
var target = $(ev.currentTarget);
var selected_data = $(ev.currentTarget).find(':selected').attr("text") <- here i want selected value;
console.log(selected_data);
}

Html select dropdownlist how to display name and id at the same time

I have been looking for same kind of question but did not find, What I want to achieve is, i want to display 'nama' and 'id' at the same time on option, so when one clicks dropdown list should show 'wick dhdfyj97' and 'abraham 15hndfj', is this possible (in javascript)? for now i have managed to display just 'nama'. This is how my json looks like :
[{"nama ": "wick","id": "dhdfyj97",},{"nama ": "abraham","id": "15hndfj",}]
Here is the code :
.then(res =>{
res.json().then(num => {
for (var o = 0; o < num.length; o++) {
var i = document.getElementById("Select");
var d = document.createElement("option");
d.text = num[o].nama;
i.add(d);
}
}
)
})
We can add both using string literals.
.then(res =>{
res.json().then(num => {
for (var o = 0; o < num.length; o++) {
var i = document.getElementById("Select");
var d = document.createElement("option");
d.text = `${num[o].nama} ${num[o].id}`;
i.add(d);
}
}
)
})
i would also suggest to query for the html tag only once and reuse it, also iterate through the response directly using for of loop:
const i = document.getElementById("Select");
for (const item of num) {
const d = document.createElement("option");
d.text = `${item.nama} ${item.id}`;
i.add(d);
}
you can learn more about template literals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
you can refer MDN for much more.
Concatenate the nama and the id together:
.then(res =>{
res.json().then(num => {
for (var o = 0; o < num.length; o++) {
var i = document.getElementById("Select");
var d = document.createElement("option");
d.text = num[o].nama + ' ' + num[o].id;
i.add(d);
}
}
)
})
Create an Option tag and assign its textContent to concatenation of item.nama and item.id and append it to the Select tag,
also you see the space in "nama " remove that,so it should be "nama" instead otherwise it's going to show undefined in the option tag
let Array = [
{ "nama": "wick", id: "dhdfyj97" },
{ "nama": "abraham", id: "15hndfj" },
];
let Select = document.getElementById("Select");
Array.map((item) => {
var d = document.createElement("option");
d.textContent = item.nama + " " + item.id;
Select.appendChild(d);
});
<select id="Select"> </select>

Create JavaScript object with an array with a multi select field

Hello I am looking to create a JavaScript object to store values captured from some fields. I have dynamic fields where the user can add more fields to the page.
I am able to capture and store the fields in an object using the below code.
var attributes = document.getElementsByName("attribute[]");
var locations = document.getElementsByName("location[]");
var len = attributes.length;
var data = []
for(var i = 0; i < len; i++){
var element = {
"Attribute": attributes[i].value,
"Location": locations[i].value,
};
data.push(element);
};
Recently I had to add a <select> field called "Methods" to the dynamic fields, that allows users to select multiple methods in the drop down. I am struggling on how I can get the array of selected methods per "Attribute".
Any help is greatly appreciated.
You can use a function as follow:
function extract(select) {
var array = [];
for (var i = 0; i < select.length; i++) {
if (select.options[i].selected) array.push(select.options[i].value);
}
return array
}
document.querySelector('button').addEventListener('click', function() {
var attributes = document.getElementsByName("attribute[]");
var locations = document.getElementsByName("location[]");
var methods = document.getElementsByName("methods[]");
var len = attributes.length;
var data = []
for (var i = 0; i < len; i++) {
function extract(select) {
var array = [];
for (var i = 0; i < select.length; i++) {
if (select.options[i].selected) array.push(select.options[i].value);
}
return array;
}
var element = {
"Attribute": attributes[i].value,
"Location": locations[i].value,
"Methods": extract(methods[i])
};
data.push(element);
};
console.log(data);
});
<input name='attribute[]' placeholder='attribute[]' value=''>
<input name='location[]' placeholder='location[]' value=''>
<select multiple name='methods[]'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
<p/>
<input name='attribute[]' placeholder='attribute[]' value=''>
<input name='location[]' placeholder='location[]' value=''>
<select multiple name='methods[]'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
<p/>
<button>Click me</button>
Let's say your select elements have a name attribute options:
var attributes = document.getElementsByName("attribute[]");
var locations = document.getElementsByName("location[]");
var options = document.getElementsByName("options[]"); //<--------
var len = attributes.length;
var data = [];
for(var i = 0; i < len; i++){
var element = {
"Attribute": attributes[i].value,
// Grab the texts of the selected options:
options: Array.from(options[i].querySelectorAll('option:checked'),
option => option.textContent),
"Location": locations[i].value,
};
data.push(element);
}
Note that you can use the Array.from callback argument (and short arrow function syntax) to create the data array:
var attributes = document.getElementsByName("attribute[]");
var locations = document.getElementsByName("location[]");
var options = document.getElementsByName("options[]");
var data = Array.from(attributes, (attrib, i) => ({
Attribute: attrib.value,
options: Array.from(options[i].querySelectorAll('option:checked'),
option => option.textContent),
Location: locations[i].value,
}));

Javascript. Change a form option based on a previous one

I'm trying to change the options that appear in my select box named session when a certain option is picked in my select box named movie.
Here's the script I've got so far.
<script>
var optionList = document.getElementsByName("movie")[0];
var movieList = ["AC", "CH", "AF", "RC"];
for(var i = 0; i < movieList.length; i++){
var movie = movieList[i];
var option = document.createElement("option");
option.textContent = movie;
option.value = movie;
optionList.appendChild(option);
}
</script>
<script>
var sessionList = document.getElementsByName("session")[0];
var actionSession = ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"];
var childrenSession = ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"];
var foreignSession = ["MON-06", "TUE-06", "SAT-06", "SUN-06"];
var romanticSession = ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"];
if(document.getElementsByName("movie")[0].value === movieList[0])
{
for(var i = 0; i < actionSession.length; i++){
var session = actionSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
}
</script>
Consider changing the Sessions to an object, like so:
var sessions = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
}
This way, you can use the onchange of your select tag to get the value of the selected option and reference the list of sessions for the appropriate movie list as such:
var category = document.getElementByName("movie").value;
var currentSession = sessions[category];
for(var i = 0; i < currentSession.length; i++){
var session = currentSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
Objects in javascript can be referenced as "key" => "value" pairs simply by following the syntax:
object = { "key": value }, and value's type can be anything - even another Object!
You can even declare object keys like such:
var sessions = {};
sessions['AC'] = [...];
sessions['CH'] = [...];
sessions.AF = [...];
sessions.RC = [...];
That's right - all of the above declarations can be referenced as sessions['xx']
Hope this simplifies things a bit.
You could create a dictionary mapping elements of movieList to lists of <option> elements, maybe?
You might call the dictionary sessionOptions. You would then change all the children of #session at once - so this would go in your onchange handler for sessionList:
var sessionList = document.getElementsByName("session")[0];
var chosenMovie = "..."; // "AC", for instance
// Remove all elements from sessionList
while(sessionList.firstChild) {
sessionList.removeChild(sessionList.firstChild);
}
// Add the chosen movie options
var chosenMovieOptions = sessionOptions[chosenMovie];
for(var i = 0; i < chosenMovieOptions.length; i++) {
sessionList.appendChild(chosenMovieOptions[i]);
}
You would also want to make a mapping of movie codes to session lists:
var SESSION_LISTS = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
};
Then, to build sessionOptions, for each "session string list" (such as actionSession), you would loop through the session list and create elements:
var currentSession = "..."; // currentSession is the current session list - "AC", for instance
var currentSessionOptions = SESSION_LISTS[currentSession];
sessionOptions[currentSession] = [];
for(var i = 0; i < currentSessionOptions.length; i++){
var session = currentSessionOptions[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionOptions[currentSession].append(option);
}
But then you would do this for every sublist in SESSION_LISTS, so you would put this code in some initializer function:
var sessions = Object.keys(SESSION_LISTS);
for(var i = 0; i < sessions.length; i++) {
currentSession = sessions[i];
// the code snippet above
}

Best way to create new DOM elements using Jquery

is it better to create a DOM element like this:-
var option='';
var objY = $('select[name="yaxis"]');
for(var key in summaryObj)
{
option += '<option value="'+summaryObj[key]+'">'+key+'</option>';
}
objY.html(option);
or like this,
var objY = $('select[name="yaxis"]');
var option = document.createElement("option");
for(var key in summaryObj)
{
var san = summaryObj[key];
objY.append($(option).clone().attr({value:san,text:key}));
}
For perfomance, this is probably among the fastest ways
var option = document.createElement("option");
var frag = document.createDocumentFragment();
for (var key in summaryObj) {
var clone = option.cloneNode();
clone.value = san;
clone.innerHTML = key;
frag.appendChild(clone);
}
$('select[name="yaxis"]').append(frag);
For readability, I like this
var objY = $('select[name="yaxis"]');
var frag = [];
$.each(summaryObj, function(key, val) {
frag.push(
$('<option />', {
value : san,
text : key
})
);
});
objY.append(frag);
In jQuery, you Do it like this:
var select = $('<select>').attr('name','yaxis');
var option = $("<option>");
option.text('word').value('word');
select.append(option);

Categories