HTML select options do not get populated with getElementById and innerHTML [duplicate] - javascript

I am attempting to create a bit of JavaScript that, on the click of a button, adds a tag filled with options. The options will be defined with an array called "roster". What I would like to see is a dropdown that has options for sanchez, ronaldo, and ozil.
var roster = [
"ozil",
"sanchez",
"ronaldo"
];
var reps = null;
var dropdown = null;
var scorerOption = "<option value='" + reps + "' class='scorerOption'>" + roster[reps] + "</option>";
function makeDropdown () {
dropdown = "<select class='scorer'>" + String(scorerOption).repeat(roster.length) + "</select>";
document.getElementById("rawr").innerHTML = dropdown;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="rawr"><button onclick="makeDropdown()">Select a player</button></p>
</body>
</html>
As you may notice, the and tags appear, but all have innerHTML's and values of "undefined". How can I change that so it displays the names sanchez, ronaldo, and ozil?

You'll need to loop through the array and for each element in the array, create and insert a new option.
You should also not use inline HTML event handling attributes (onclick), see here for why.
Lastly, it's generally better to create dynamic elements with the DOM API call of document.createElement(), rather than build up strings of HTML as the strings can become difficult to manage and the DOM API provides a clean object-oriented way to configure your newly created elements.
var roster = [
"ozil",
"sanchez",
"ronaldo"
];
// Work with your DOM elements in JavaScript, not HTML
var btn = document.getElementById("btn");
btn.addEventListener("click", makeDropdown);
function makeDropdown () {
// Dynamically generate a new <select> element as an object in memory
var list = document.createElement("select");
// Configure the CSS class for the element
list.classList.add("scorer");
// Loop over each of the array elements
roster.forEach(function(item){
// Dynamically create and configure an <option> for each
var opt = document.createElement("option");
opt.classList.add("scorerOption");
opt.textContent = item;
// Add the <option> to the <select>
list.appendChild(opt);
});
// Add the <select> to the document
document.getElementById("rawr").appendChild(list);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="rawr"><button id="btn">Select a player</button></p>
</body>
</html>

Related

Issue with getting a keyup function to get sum of input field values using plain Javascript

I'm working on a personal project and I've run into an issue that I haven't been able to solve.
Here is a function that generates new table rows into a table (with id of "tableData") when a button is clicked:
function addNewRow(){
var tableEl = document.getElementById("tableData");
var newLine = '<tr class="newEntry">';
var classArray = ["classA", "classB", "classC", "classD"];
for (var i = 0; i < classArray.length; i++){
newLine += '<td><input class="' + classArray[i] + '"></td>';
}
newLine += '</tr>';
tableEl.insertAdjacentHTML("beforeend", newLine);
}
document.getElementById("addRow").addEventListener("click", addNewRow, false);
//the element with id="addRow" is a button
I've simplified the code for the above function for the sake of readability as it's not the focus of the problem. When the button is clicked, a new row is added successfully.
The problematic part involves another function that takes the sum of the respective classes of each row and displays them in a div.
The goal is to get the sum of the values of all input fields with matching class names. For example, let's say I use the addNewRow function to get six rows. Then I want to have the div showing the sum of the values of all input fields with the class name of "classA"; the number in that div should be the sum of those six values, which gets updated as I type in the values or change the existing values in any of the input fields with class name of "ClassA".
function sumValues(divId, inputClass){
var sumVal = document.getElementsByClassName(inputClass);
var addedUp = 0;
for (var j = 0; j < sumVal.length; j++){
addedUp += Number(sumVal[j].value);
}
document.getElementById(divId).innerHTML = addedUp;
}
Here are a couple (out of several) failed attempts:
document.input.addEventListener("keyup", sumValues("genericDivId", "classA"), false);
document.getElementsByClassName("classA").onkeyup = function(){sumValues("genericDivId", "classA");}
Unfortunately, after scouring the web for a solution and failing to find one, I just added an event listener to a button that, when clicked, would update the div to show the sum of values. Also had to modify the sumValues function to take values from an array rather than accepting arguments.
My question is: How can I modify the code so that the sum value updates as I type in new values or change existing values using pure Javascript (vanilla JS)?
You are very close, document.getElementsByClassName() returns an array of DOM objects, you need to set the onkeyup function for each and every element by looping through that array.
var classA = document.getElementsByClassName('classA'); // this is an array
classA.forEach(function(elem){ // loop through the array
elem.onkeyup = function(){ // elem is a single element
sumValues("genericDivId", "classA");
}
}
Hopefully this fixes your issue
Maybe the example below is not same with your situation, but you'll get the logic, easily. Anyway, do not hesitate to ask for more guide.
document.getElementById("row_adder").addEventListener("click", function() {
var t = document.getElementById("my_table");
var r = t.insertRow(-1); // adds rows to bottom - change it to 0 for top
var c = r.insertCell(0);
c.innerHTML = "<input class='not_important_with_that_way' type='number' value='0' onchange='calculate_sum()'></input>";
});
function calculate_sum() {
var sum = ([].slice.call(document.querySelectorAll("[type=number]"))).map(e=>parseFloat(e.value)).reduce((a, b) => a+b);
document.getElementById("sum").innerHTML = sum;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<p>
<strong>Sum</strong>:<span id="sum">0</span>
</p>
</div>
<button id="row_adder">
Click me
</button>
<table id="my_table">
</table>
</body>
</html>

Making table with objects in array?

I'm a beginner in javascript and I have a little problem with my code. I found an exercise and i'm trying to do it. I have to write a function that will insert text from variable into table. I never met something like this. This variable looks like four objects in array. I want to show text in the table when I press a button. There are two buttons. When I press "Fizyka" button i should see:
Fizyka
Ola Kowal
Ela Nowak
and when I press "Chemia":
Chemia
Ala Goral
Ula Szpak
So this is my code. All i can edit is function show(study):
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"></div>
<script>
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
if (study==='fizyka')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
if (study==='chemia')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
}
</script>
</body>
</html>
It's not working. I don't know how to insert text from this variable into table.
There is several problem with your code. I have written piece of code which is working and you can use it and inspire.
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"><h2></h2><ul></ul></div>
<script>
//Student array
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
console.log('ENTER show('+study+')');
//Select h2 element
var header = document.getElementById("list").firstChild;
//Set h2 element text
header.innerHTML = study;
//Select ul element
var list = document.getElementById("list").lastChild;
//Set inner html to empty string to clear the content
list.innerHTML = "";
//loop through students and set the appropriate html element values
for(var i = 0; i < student.length; i++){
//check whether student[i] studies study which is put as a paramter into the function
if(student[i].study === study){
//Create new li element
var li = document.createElement('li');
//Into li element add a new text node which contains all data about the student
li.appendChild(document.createTextNode(student[i].name + ' ' + student[i].second_name));
//add li element into ul
list.appendChild(li);
}
}
console.log('LEAVE show('+study+')');
}
</script>

JavaScript onclick functions unbound due to innerHTML usage

I have a function in javascript that I intend to use to create/add a link to a 'subLink' div, and add an onclick event to this link that loads associated 'content' to a contentDiv:
function addSubLink(text, name, content) {
// append programLink span to subLinks:
document.getElementById("subLinks").innerHTML += "<span class=\"programLink\" id=\"" + name + "\">" + text + "</span>";
// load program content onclick:
document.getElementById(name).onclick = function () {
// set value of programContent to content's value
document.getElementById("programContent").innerHTML = content;
}
}
This function would be called, for example, by loadAboutPage() to populate the subLink div
var whatContent = "<p>A website!</p>";
var whyContent = "<p>Recreation!</p>";
var howContent = "<p>Kludges.</p>";
addSubLink("WHAT", "whatLink", whatContent);
addSubLink("WHY", "whyLink", whyContent);
addSubLink("HOW", "howLink", howContent);
The problem is that only the last subLink has an onclick event attached to it (content is loaded and css class changed). That is, it creates WHAT, WHY, and HOW links, but only appends the onclick function to the last called: HOW, in this case.
I'm very rusty when it comes to JavaScript, so I have no idea if it's a result of my lack of knowledge about anonymous functions, or using the local 'name' variable incorrectly, or anything else completely different. I've searched for awhile, but it seems I'm too ignorant to even figure out what a similar problem would be!
Anyway, I greatly appreciate your help! Thanks in advance!
EDIT:
Here's a complete HTML example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Stack Overflow Example</title>
<script type="text/javascript">
function addSubLink(text, name, content) {
document.getElementById("subLinks").innerHTML += "<span class=\"programLink\" id=\"" + name + "\">" + text + "</span>";
document.getElementById(name).onclick = function () {
document.getElementById("program").innerHTML = content;
}
}
window.onload = function() {
var whatContent = "<p>A website!</p>";
var whyContent = "<p>Recreation!</p>";
var howContent = "<p>Kludges.</p>";
addSubLink("WHAT", "whatLink", whatContent);
addSubLink("WHY", "whyLink", whyContent);
addSubLink("HOW", "howLink", howContent);
}
</script>
</head>
<body>
<div id="container">
<div id="programWindow">
<div id="subLinks"> </div>
<div id="program"> </div>
</div>
</div>
</body>
</html>
The issue is due to:
....innerHTML += "...";
By setting innerHTML, all existing child elements are first removed, then the markup is parsed to create new elements. So, while the original "WHAT" and "WHY" spans did have onclick bindings, they've being replaced by similar elements that don't.
To append a new element and keep state, you'll want to use DOM methods like createElement(), appendChild(), and createTextNode() (or set textContent/innerText):
function addSubLink(text, name, content) {
var span = document.createElement('span');
span.className = 'programLink';
span.id = name;
span.appendChild(document.createTextNode(text));
// append programLink span to subLinks:
document.getElementById('subLinks').appendChild(span);
// load program content onclick:
span.onclick = function () {
// set value of programContent to content's value
document.getElementById("programContent").innerHTML = content;
};
}
Example: http://jsfiddle.net/bG7Dt/

Does not append input strings dynamically on the web page

I am new in Javascripting language.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT CODE
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the input Array, but unable to show on the web page. Need help please.
Tell me one more thing there is one code on given link. It also not gives desired answer. Please help me overcome from this problem.
<html>
<body>
<script>
function addValue(a) {
var element1 = document.createElement('tr');
var element2 = document.createElement('td');
var text = document.createTextNode(a);
var table = document.getElementById('t');
element2.appendChild(text);
element1.appendChild(element2);
table.tBodies(0).appendChild(element1);
}
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</body>
</html>
In your code where you push an item to the end of your input array, you're trying to push the array instead of the value to the array. So if your problem is that your values aren't being appended to the page is because you're trying to append the array that's empty initially onto itself.
So instead of
input.push(input);
It should be
input.push(s);
Since "s" you already declared to be the value from the text field.
And if you're not going to use that parameter you're passing in, I would get rid of it.
References: Javascript Array.Push()

Adding charts dynamically with flot

I'm running the following code. The button basically adds a chart into the html page. The problem I'm facing is: when I click on the button for the second time, the curve of the former chart fades away (though the labels don't), and I want it to stay. I've tried to debug and this happens when I modify the innerHTML property right at the beginning of the buttonClicked javascript function. Can anybody tell me why is this happening?
<html>
<head>
<title>Configurando gráficos</title>
<script language="javascript" type="text/javascript" src="../scripts/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../scripts/jquery.flot.js"></script>
<script type="text/javascript" language="javascript">
var id = 0;
function requestGraph(placeholder) {
$.ajax({url: "../requests/get_xml_oid.php?oid=1.3.6.1.2.1.2.2.1.10.65540&host=200.234.199.161", success: function(request){
// Initialize dataToDraw to an empty array
var dataToDraw = [];
// The first tag is called ifInOctets
var ifInOctetsEl = request.getElementsByTagName("ifInOctets")[0];
// Store the data element, to loop over the time-value pairs
var dataEl = ifInOctetsEl.getElementsByTagName("data");
// For each data element, except the first one
var i;
for (i=1; i<dataEl.length; i++){
// get the time-value pair
var timeEl = dataEl[i].getElementsByTagName("time")[0];
var valueEl = dataEl[i].getElementsByTagName("value")[0];
var time = timeEl.textContent;
var value = valueEl.textContent;
// get the value of the former data element
// Warning: the former value in the XML file is newer than the latter
var formerValueEl = dataEl[i-1].getElementsByTagName("value")[0];
var formerValue = formerValueEl.textContent;
// push to the dataToDraw array
dataToDraw.push( [parseInt(time)*1000, parseInt(formerValue) - parseInt(value)]);
}
// tell the chart that the x axis is a time variable
var options = {
xaxis: { mode: "time"}
};
// plot the chart and place it into the placeholder
jQuery.plot(jQuery(placeholder), [dataToDraw], options);
}});
}
function buttonClicked() {
document.getElementById("body").innerHTML += "<div id=\"placeholder" + id + "\" style=\"width:600px;height:300px;\"></div>";
requestGraph("#placeholder" + id);
setInterval("requestGraph(\"#placeholder" + id + "\")",60000);
id = id + 1;
}
</script>
</head>
<body id="body">
<button type="button" onClick="buttonClicked()">Click Me!</button>
</body>
</html>
According to this previous question, assigning to innerHTML destroys child elements. It's not clear to me that this is exactly what you're seeing, but perhaps using document.createElement as suggested in the similar question will work for you as well.

Categories