Creating a dropdown list with hyperlinked items in an array - javascript

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>

Related

Setting multiple values for option using javascript (add)

<!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>

Cannot read property 'undefined' of undefined? why this error is coming?

var select = document.getElementById("source");
var select2= document.getElementById("status");
var option = ["1", "2", "3", "4", "5","6","7","8","9"];
var option2= [];
function moveright() {
var a = source.options[source.selectedIndex].value;
var option = document.createElement("option");
option.text = a;
select2.add(option);
select.remove(i);
}
function moveleft() {
var b = status.option2[status.selectedIndex].value;
var option2 = document.createElement("option");
option2.text = b;
select.add(option2);
select2.remove(i);
}
for(i = 0; i < option.length; i++) {
var opt = option[i];
var a = document.createElement("option");
a.innerHTML = opt;
a.value = opt;
select.appendChild(a);
}
for(i = 0; i < option2.length; i++) {
var opt2 = option2[i];
var a = document.createElement("option");
a.innerHTML = opt2;
a.value = opt2;
select2.appendChild(a);
}
<select id = "source" multiple size = "10" onclick = "moveright ()">
<option>Choose a number</option>
</select>
<select id = "status" multiple size = "10" onclick = "moveleft ()">
<option>Choose a number </option>
</select>
I am new to JavaScript I am trying to push the drop down values from one drop down to another. First drop down is working, but second drop down is not working. Can anyone help me? I tried only in the JavaScript array.
Slightly changed, but giving you expected results ;)
Working fiddle
In your moveright and moveright you had a variable i which was not defined. I assume you wanted to use selected option index to remove itself.
And you should write full selector for getting elements, not using it's id directly. Browser picked up source id and returned as html element, however it could not do that with status, because there is such property as window.status.

Creating a html dropdown list with the contents of a SQLite field

I am trying to make an SQLite field the contents of a drop down list in html using embedded JavaScript. This is the code I have but it does not work.
<select>
<option value="default">Select a test to edit</option>
<script>
var db = openDatabase('ExamSQL', '1.0', 'database')
db.transaction(function (tx) {
tx.executeSql('SELECT Questions FROM Question',[],function(tx,questions);
{
var len = questions.rows.length, i;
for (i = 0; i < len; i++) {
</script><option value="name"><script>
document.write(questions.rows.item(i).text)
document.getElementById("name").innerHTML=questions.rows.item(i).text
</script></option>
<script>
}
});
</script>
</select>
Can anyone help?
Edit: I did this after BrokenBinary's comment
<select id="section_list">
<option value="default">Select a section the question is in</option>
<script>
var db = openDatabase('ExamSQL', '1.0', 'database')
db.transaction(function (tx) {
tx.executeSql('SELECT SectionName FROM Section',[],function(tx,sections);
{
var select=document.getElementById('section_list')
var len = sections.rows.length, i;
for (i = 0; i < len; i++) {
var option = document.createElement('option');
option.text=sections.rows.item(i).text;
option.value=sections.rows.item(i).text;
select.appendChild(option);
}
}
});
</script>
</select>
And it sill doesn't work. Any more suggestions?
You can't close your <script> tag in the middle of your loop. Instead, you should create the <option> element in javascript and then append it to your <select> element.
So your loop would look something like this:
// Give your select an ID and use it here
var select = document.getElementById('my-select');
var len = questions.rows.length, i;
for (i = 0; i < len; i++) {
var option = document.createElement('option');
option.text = questions.rows.item(i).text;
option.value = questions.rows.item(i).text;
select.appendChild(option);
}

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);
}
}

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