Setting multiple values for option using javascript (add) - javascript

<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
for (let i=0;i<10;i++)
{
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text="+i;
option.value = i;
select.add(option);
}
function selectchange()
{
alert(document.getElementById("selectid").value);
}
</script>
</body>
</html>
Description
Here i have been using javascript to add options for my select tag
I Needed
I need to store more than one data using my existing javascript code like for value=1 option need to add another value for the option tag like value2=a, and for value=2 as value2=b
Example syntax
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text="+i;
option.value = i;
option.value2 = a;
select.add(option);
I need to add two values for my option using the above syntax.

You can try using setAttribute and getAttribute.
<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
for (let i=0;i<10;i++) {
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text="+i;
option.value = i;
option.setAttribute("data", Math.random());
option.setAttribute("data1", `data1_${Math.random()}`);
select.add(option);
}
function selectchange() {
const select = document.getElementById("selectid");
const data = select.options[select.selectedIndex].getAttribute("data");
const data1 = select.options[select.selectedIndex].getAttribute("data1");
console.log(`value is: ${select.value} and data is: ${ data } data1 is: ${data1}`);
}
</script>
</body>
</html>
Hope this is what you were looking for!!

The first solution is to use data attributes:
<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
for (let i = 0; i < 10; i++) {
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" + i;
option.value = i;
option.dataset['var-1'] = i;
option.dataset['var-2'] = 'value2';
option.dataset['var-3'] = 'value3'; // and etc.
select.add(option);
}
function selectchange() {
const selectedOption = document.getElementById("selectid").selectedOptions[0]
console.log(selectedOption.dataset);
}
</script>
</body>
</html>
The second solution is to use an external variable to store additional data:
<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
const dataStore = {};
for (let i = 0; i < 10; i++) {
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" + i;
option.value = i;
select.add(option);
dataStore[i] = {
var1: i,
var2: 'var2',
var3: 'var3'
};
}
function selectchange() {
const index = document.getElementById("selectid").value
const value = dataStore[index]
console.log(value);
}
</script>
</body>
</html>

Related

How can I load this select input field with options passed using JS?

When loading an HTML table, there is this select input field, which should make available some options.
Right after the HTML table row is built, I'm calling a function, which should populate this input field, getting it by its class.
Here is the HTML piece and the function:
function loadTelaOptions(telaOptions) {
telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
document.querySelector('tableBodySelect').value = '';
let selectList = document.querySelector('tableBodySelect');
let options = selectList.getElementsByTagName('option');
for (let i = options.length; i--;) {
selectList.removeChild(options[i]);
}
let option = document.createElement("option");
option.value = "";
option.text = "";
selectList.appendChild(option);
telaOptions.forEach(function(item, index) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.text = item;
selectList.appendChild(option)
});
}
<td>
<select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
</select>
</td>
Appreciate any help!
Your selectors for .querySelector('tableBodySelect') doesn't match your desired elements. You try to match the classes, therefore you need to prepend a . to your selector .querySelector('.tableBodySelect')
This does already resolve your issue.
function loadTelaOptions(telaOptions) {
telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
document.querySelector('.tableBodySelect').value = '';
let selectList = document.querySelector('.tableBodySelect');
let options = selectList.getElementsByTagName('option');
for (let i = options.length; i--;) {
selectList.removeChild(options[i]);
}
let option = document.createElement("option");
option.value = "";
option.text = "";
selectList.appendChild(option);
telaOptions.forEach(function(item, index) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.text = item;
selectList.appendChild(option)
});
}
loadTelaOptions();
<td>
<select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
</select>
</td>

Creating a dropdown list with hyperlinked items in an array

I'm very new to JS, so forgive the simplicity of this question... Trying to create a dropdown list with hyperlinked items using an array. The end product will have hundreds of entries, so it's important to save space.
Two things to keep in mind: I can't use JQuery and I have to integrate this in WordPress.
I know I'm doing this incorrectly, but the below code should give an accurate idea of what I'm trying to do. Any help much appreciated.
<body>
<form id="siteList">
<select id="selectSite">
<option>Choose a site</option>
</select>
</form>
</body>
</script>
var myArray = new Array("Google", "Yahoo", "Bing", "Gmail", "Facebook");
var links = new Array("http://www.google.com", "http://www.yahoo.com", "http://www.bing.com", "http://www.gmail.com", "http://www.facebook.com");
// Get dropdown element from DOM
var dropdown = document.getElementById("selectSite")
// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
// Append the element to the end of Array list
dropdown[dropdown.length] = new Option(myArray[i].link(links[i]), myArray[i].link(links[i]));
}
</script>
http://jsfiddle.net/L2awjmvd/
You have to write the code like below:
<script type="text/javascript">
function createarray() {
var myArray = new Array("Google", "Yahoo", "Bing", "Gmail", "Facebook");
var links = new Array("http://www.google.com", "http://www.yahoo.com", "http://www.bing.com", "http://www.gmail.com", "http://www.facebook.com");
var dropdown = document.getElementById("selectSite");
for (var i = 0; i < myArray.length; ++i) {
var option = document.createElement("option");
option.text = myArray[i];
option.value = links[i];
dropdown.add(option);
// dropdown[dropdown.length] = new Option(myArray[i].link(links[i]), myArray[i].link(links[i]));
}
}
function selectSiteRedirect(selectedSite) {
window.location.href = selectedSite;
}
</script>
<body onload="createarray();">
<form id="siteList">
<select id="selectSite" onchange="selectSiteRedirect(this.value);">
<option>Choose a site</option>
</select>
</form>
</body>
I think this is the correct way to do it:
<script>
var my_array = ["Google", "Yahoo", "Bing"];
var my_array_links = ["www.google.com", "www.yahoo.com", "www.bing.com"];
var select = document.getElementById("selectSite");
for (i = 0; i < my_array.length; i++) {
var opt = document.createElement('option');
opt.value = my_array[i];
opt.innerHTML = my_array_links[i];
select.appendChild(opt);
}
</script>
Here is http://jsfiddle.net/fvjeunbu/
If you want to redirect when the user select an option, then the select declaration should be:
<select id="selectSite" onchange="javascript: window.location.assign(this.value);">
<script>
function pageLoad() {
var my_array = ["Google", "Yahoo", "Bing"];
var my_array_links = ["www.google.com", "www.yahoo.com", "www.bing.com"];
var select = document.getElementById("selectSite");
for (i = 0; i < my_array.length; i++) {
var opt = document.createElement('option');
opt.value = my_array_links[i];
opt.innerHTML = my_array[i];
select.appendChild(opt);
}
}
window.onload = pageLoad;
function selectSiteRedirect(selectedSite) {
// window.location.href = selectedSite;
if(selectedSite!="selected")
window.open(selectedSite, '_blank');
}
</script>
<div>
<select id="selectSite" onchange="selectSiteRedirect(this.value)">
<option selected="selected" value="selected">Choose a site</option>
</select>
</div>

Replacing option in select field (not adding)

I have a select field as follows:
<select id="field">
I add options based on values found in another div (OtherDiv) on my page like this:
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}
However, I would like to set up some alternative value for the field to show, if there are no matches to the regex. How would I best achieve that?
Use if condition
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
if(result.length){
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}else{
//add alternative options here
var option = document.createElement("option");
option.innerHTML = "No records found"; //whatever text you want to show
select.add(option);
}
}

Auto populate option tag not working java script

I'm trying to populate number in select - option tag .But my script fills number at only one select tag
HTML :
<div class="form_row">
<label>Week Num</label>
<select class="form_select1" id="weeknum"></select>
<b class="bold1">&nbsp TO &nbsp</b>
<select class="form_select1" id="weeknum1"></select>
</div>
Javascript :
<script>
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
select1.add(option, 0);
}
</script>
How do i achieve that ?
You can add an element only once to a parent node, so you need to create another option element:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}
Here's the JSFIddle.
Try this ...
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option1, 0);
var option2 = document.createElement('option');
option2.text = option2.value = i;
select1.add(option2, 0);
... creating a distinct "option" for each select list. The created elements cannot be reused.
You need to create a distinct option element for each list. A given DOM element can only be in one place in the DOM.
edit: I see it's already answered... well, my first answer :)
try this:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
var option1 = document.createElement('option');
option.text = option.value = option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

Categories

Resources