Fill a <select> using JavaScript - javascript

So I want to add a dropdown in my form that will display numbers from 1 to 999 .
I have tried to do it using JS but it doesn't work
Here is what I have tried so far :
<html>
<head>
<script>
window.onload = fillDropDown();
function fillDropDown() {
var ddl = document.getElementById( 'myDropdown' );
var theOption = new Option;
var x;
var i;
for(i = 0; i < 999; i++) {
x = i + 1;
theOption.text = x;
theOption.value = x;
ddl.options[i] = theOption;
}
}
</script>
</head>
<body>
<form id="myForm">
<select id="myDropdown"></select>
</form>
</body>
But it doesn't work .
Here is a jsfiddle example http://jsfiddle.net/j3nLxptn/

It works if you instantiate the option inside the loop:
for (i = 0; i < 999; i++) {
var theOption = new Option;
x = i + 1;
theOption.text = x;
theOption.value = x;
ddl.options[i] = theOption;
}
See http://jsfiddle.net/j3nLxptn/1/

The issue is that you are always reusing the same option element. You have to create a new Option instance at every iteration and that you can use add to actually append select options.
Also note that the Option constructor can take text and value parameters.
for (i = 0; i < 999; i++) {
x = i + 1;
ddl.add(new Option(x, x), null);
}

Related

Converting form text in HTML into an array in JS

I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview

Generate option select on input change

<select id="gameid">
//<option is a number 1-999>
</select>
<select id="netid">
//<option is a number 1-999>
</select>
<select id="camp_id">
<script>
var a = $("#gameid").val();
var b = $("#netid").val();
var c = a+b;
for (var i = 1; i<=999; i++)
{
document.write("<option value='"+c+i+"'>"+c+i+"</option>");
}
</script>
</select>
The code above is to generate some options into selection.
What I want to do there is, if the val in the #gameid is changed, the option list will change too, and so does for the #netid.
However, the option doesn't change. It stay in the default value of the #gameid and #netid.
I don't know what I am missing here. I need a help, please.
[UPDATE]
This code almost work. However, when I do the second change on the #cameid after all I have been select, it doesn't change the #campid selection anymore. It will do change it again if I do the change too on the #netid.
$("#gameid" && "#netid").on('change', function(){
a = $("#gameid").val(),
b = $("#netid").val(),
c = a+b;
$("#camp_id").empty();
for (var i = 1; i<=999; i++){
$("#camp_id").append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
Use something like this:
var options = '';
for (var i = 1; i<=999; i++)
{
options += "<option value='"+c+i+"'>"+c+i+"</option>";
}
document.getElementById('camp_id').innerHTML = options;
Use similar to insert options to other select boxes if needed
Don't forget to add Jquery library,
<select id="gameid" onchange="generateOptions();">
<!-- Your Options -->
</select>
<select id="netid" onchange="generateOptions();">
<!-- Your Options -->
</select>
<select id="camp_id">
</select>
<script type="text/javascript">
var a,b,c,str="";
function generateOptions()
{
a = $("#gameid").val();
b = $("#netid").val();
c = a+b;
for (var i = 1; i<=999; i++)
{
str= str + "<option value='"+c+i+"'>"+c+i+"</option>";
}
$('#camp_id').html(str);
}
</script>
var a = $("#gameid").val(),
b = $("#netid").val(),
c;
$("#gameid").change(function(){
a = $(this).val();
c = parseInt(a)+parseInt(b);
$("#camp_id").empty();
for (var i = 1; i<=999; i++){
$("#camp_id").append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
https://jsfiddle.net/partypete25/j9toh39c/
Use change event
$('#gameid,#netid').on('change',function (){
var a = $("#gameid").val();
var b = $("#netid").val();
alert($(this).attr('id'));
var c = parseInt(a)+parseInt(b);
if ( $(this).attr('id') == 'gameid') {
$el = $("#netid");} else {$el = $("#gameid")};
$el.text('');
for (var i = 1; i<=999; i++)
{
$el.append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
note: I used jquery, jsfiddle: https://jsfiddle.net/1zgre9pw/4/
As you want to add options to HTML select dynamically. I have tried to achieve the same using jquery i.e. to be call on $('#gameid').populate();.
Firstly, Add jquery library in <head> of page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>`
WORKING DEMO
$.fn.populate = function () {
var $this = $(this);
for (var i = 1; i<=999; i++){
$this.append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
}
$('#gameid').populate();
You can add same for second select(drop-down) as well.

array elements added or missing in javascript function

This code appends an extra element to the first generated menus every time the function is called. The last element in each array is missing in all subsequent calls. I can't seem to figure out why this is happening.
<script type="text/javascript" language="javascript">
var elements = ['one','two','three','etc'];
var positions = ['Producer', 'Tech', 'Assist', 'Voice'];
function addNamelist() {
var q = document.createElement('select');
for (var j=0; j<positions.length; j++) {
q.setAttribute('id', positions[j]);
document.body.appendChild(q);
var r = document.createElement('option');
r.setAttribute('value', positions[j]);
var m = document.createTextNode(positions[j]);
r.appendChild(m);
document.getElementById(positions[j]).appendChild(r);
}
var y = document.createElement('select');
for (var i = 0; i < elements.length; i++) {
y.setAttribute('id', elements[i]);
document.body.appendChild(y);
var z = document.createElement('option');
z.setAttribute('value', elements[i]);
var t = document.createTextNode(elements[i]);
z.appendChild(t);
document.getElementById(elements[i]).appendChild(z);
}
}
</script>
</head>
<body>
<form action="editpageentry.php"><form>
create field
</body>
</html>

A bit stuck with the "triangle" program in Javascript

I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>

Why is this function not executing on page load? (How to create HTML option using JavaScript at page load)

I want to fill a dropdown list and I've written the following code:
<script language="JavaScript1.2">
window.onload = fillDropDown();
function fillDropDown() {
var ddl = document.getElementById("dia");
var theOption = new Option;
var x;
var i;
for(i = 1; i < 32; i++) {
x = i + 1;
theOption.text = x;
theOption.value = x;
ddl.options[i] = theOption;
}
}
</script>
<body>
<form>
<select id=dia></select>
</form>
<body>
It isn't working, any idea why?
You have some errors in your code.
1. The first common mistake is the following:
window.onload = fillDropDown();
This previous code is registering the result of the called function fillDropDown and then assigning its results into window.onload. Thus, this will never do something. To register an event you have to assign a function not the result of a called function. The difference is this:
window.onload = fillDropDown; // Without the parentheses.
2. Another mistake I found, is about the creation of the option element. The better way to create HTML element in JavaScript is using the almost-standard document.createElement function.
3. Also your HTML markup has an error. Your select is written: <select id=dia></dia> and it should be <select id="dia"></select>;
So, with all theses changes highlighted the resulting code will be like this:
window.onload = fillDropDown;
function fillDropDown() {
var ddl = document.getElementById("dia");
var theOption;
var x;
var i;
for (i = 1; i < 32; i++) {
x = i + 1;
theOption = document.createElement('option');
theOption.label = x;
theOption.value = x;
ddl.add(theOption, null);
}
}​
And it works like a charm. You can see it in action in this live demo: http://jsfiddle.net/dyjLS/
Note: I highly recommend to use a JavaScript library such as jQuery to do this, since it will deal with almost all the cross-browser inconsistencies. If you use it, your code will look like the following:
<script type="text/javascript">
jQuery( document ).ready( function($) {
var $select = $('#dia');
for ( var i = 1 ; i < 32 ; i++) {
var x = i + 1;
$select.append('<option value='+ x +'>'+ x +'</option>');
}
});
</script>
¡Voilà!
<script language="JavaScript1.2"> should be <script type="text/javascript">Also window.onload = fillDropDown(); should be window.onload = fillDropDown;

Categories