Looping through text boxes, using id as a variable? - javascript

Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.

jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>

This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}

If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>

Related

javascript undefined error - getting a value from a form

I'm a beginner! I started to study javascript, but there is an error what I can't find a way to solve it.
Uncaught TypeError: Cannot read property 'value' of undefined
at correct (homework.jsp:50)
at HTMLInputElement.onclick (homework.jsp:63)
It happens when I put the 'done' button. I wanted to get a value from a form. But the value is always 'undefined' and I couldn't change it to Number or String. Maybe I failed from getting the value. Could you kindly help me?
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h2>Homework</h2>
<form name="gugu">
<script type="text/javascript">
//How many questions?
var size=eval(window.prompt("How many questions?"));
var a=new Array(size);
var b=new Array(size);
var ans=new Array(size);
var rst=new Array(size);
var count=0;
//Start
gugugu();
function gugugu() {
document.write("<table border='1'>");
for (var i=0; i<size+1; i++) {
if(i<size) {
document.write("<tr>");
document.write("<td>");
a[i]=parseInt(Math.random()*9)+1;
b[i]=parseInt(Math.random()*9)+1;
rst[i]=a[i]*b[i];
document.write(a[i]+"*"+b[i]+"=");
document.write("</td>");
document.write("<td>");
//I can't get the value!
var str="<input type='text' name='"+i+"'>";
document.write(str);
document.write("</td>");
document.write("</tr>");
} else {
document.write("<tr>");
document.write("<td colspan='2' align='center'>");
document.write("<input type='button' value='done' onclick='correct()'>");
document.write("<input type='button' value='reset' onclick='reset()'>");
document.write("</td>");
document.write("</tr>");
}
}
document.write("</table>");
document.write("count : ");
document.write("<input type='text' value='' name='count' readonly>");
document.write("<br>");
document.write("note : ");
document.write("<input type='text' value='' name='note' readonly>");
}
function correct() {
for (var i=0; i<size;i++) {
//Here I tried putting values into an Array, but 'undefined' happens!
ans[i]=String(document.gugu.i.value);
document.write(typeof(ans[i])+","+rst[i]+"<br>");
if(ans[i]==rst[i]) {
count=count+1;
}
}
document.gugu.count.value=eval(count);
document.gugu.note.value=eval(count*10);
}
function reset() {
clear();
gugugu();
}
</script>
</form>
"gugu" its the form name, document.gugu is undefined, because its not a global variable, to get the form: document.getElementsByName("gugu");
ans[i]=String(document.gugu.i.value);
then after getting the form (in an HTMLElement[] type), you are trying to get a row?, you cant do FORM.i, "i" has no context here, access it from the array ans[], this way you can get the value from the input by their name (numbers you set as name):
ans[i] = String(document.getElementsByName("" + i)[0].values[i]);
So with a few changes here and there this works:
<h2>Homework</h2>
<form name="gugu">
<script type="text/javascript">
//How many questions?
var size = eval(window.prompt("How many questions?"));
var a = new Array(size);
var b = new Array(size);
var ans = new Array(size);
var rst = new Array(size);
var count = 0;
//Start
gugugu();
function gugugu() {
document.write("<table border='1'>");
for (var i = 0; i < size + 1; i++) {
if (i < size) {
document.write("<tr>");
document.write("<td>");
a[i] = parseInt(Math.random() * 9) + 1;
b[i] = parseInt(Math.random() * 9) + 1;
rst[i] = a[i] * b[i];
document.write(a[i] + "*" + b[i] + "=");
document.write("</td>");
document.write("<td>");
var str = "<input type='text' name='in" + i + "'>";
document.write(str);
document.write("</td>");
document.write("</tr>");
} else {
document.write("<tr>");
document.write("<td colspan='2' align='center'>");
document.write("<input type='button' value='done' onclick='correct()'>");
document.write("<input type='button' value='reset' onclick='reset()'>");
document.write("</td>");
document.write("</tr>");
}
}
document.write("</table>");
document.write("count : ");
document.write("<input type='text' value='' name='count' readonly>");
document.write("<br>");
document.write("note : ");
document.write("<input type='text' value='' name='note' readonly>");
}
function correct() {
console.log("correct");
for (var i = 0; i < size; i++) {
ans[i] = parseInt(document.getElementsByName("in" + i)[0].value);
console.log(ans[i]);
console.log(rst[i]);
if (ans[i] === rst[i]) {
count = count + 1;
}
}
console.log(count);
document.getElementsByName("count")[0].value = count;
document.getElementsByName("note")[0].value = (count * 10);
}
function reset() {
clear();
gugugu();
}
</script>
</form>
I think you can't access html elements like this document.something. Check this to see the different ways to access html elements using JavaScript.

Javascript wrong variable type

Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good

Field updates for a second then disapears

so i made a field status as p paragraph, and it supposed to be able to hold a value after button click but it only appears momentary and disappears
the library js just has the array required to fill in the data needed
<script src="library.js"></script>
<b id="chakra"></b>
<div id="planet"></div>
<script>
var index = setChakra(0);
var planetConection = "";
function setChakra(index){
document.getElementById("chakra").innerHTML = chakra[index];
while (index < chakra.length){
getPlanets(index);
if (index < chakra.length-1) index++;
else index = 0;
break;
}
return index;
}
function getPlanets(chakra){
var planetIndex = 0;
document.getElementById("planet").innerHTML = "";
while( planetIndex < chakraPlanets[chakra].length){
document.getElementById("planet").innerHTML = document.getElementById("planet").innerHTML + planetDesc[chakraPlanets[chakra][planetIndex]] +
"<form>" +
"<input id=\"planetStatus" + planetIndex + "\" type=\"text\" name=\"plntStat\">" +
"<button onclick=\"getPlanetConection(" + planetIndex + ")\">Click Me!</button>" +
"</form>" +
"<p id=\"status\"></p>";
planetIndex++;
}
}
function getPlanetConection(planetIndex){
planetConection = document.getElementById("planetStatus" + planetIndex).value;
document.getElementById("status").innerHTML = planetConection;
}
</script>
<button onclick = "index = setChakra(index)" >Click Me!</button>
Ok solved it button is meant to be input if i am not refreshing the page
<script src="library.js"></script>
<b id="chakra"></b>
<div id="planet"></div>
<script>
var index = setChakra(0);
var planetConection = "";
function setChakra(index){
document.getElementById("chakra").innerHTML = chakra[index];
while (index < chakra.length){
getPlanets(index);
if (index < chakra.length-1) index++;
else index = 0;
break;
}
return index;
}
function getPlanets(chakra){
var planetIndex = 0;
document.getElementById("planet").innerHTML = "";
while( planetIndex < chakraPlanets[chakra].length){
document.getElementById("planet").innerHTML = document.getElementById("planet").innerHTML + planetDesc[chakraPlanets[chakra][planetIndex]] +
"<form>" +
"<input id=\"planetStatus" + planetIndex + "\" type=\"text\" name=\"plntStat\">" +
"<input value=\"Click\" type=\"button\" onclick=\"getPlanetConection(" + planetIndex + ")\"/>" +
"</form>" +
"<p id=\"status" + planetIndex + "\"></p>";
planetIndex++;
}
}
function getPlanetConection(planetIndex){
planetConection = document.getElementById("planetStatus" + planetIndex).value;
document.getElementById("status" + planetIndex).innerHTML = planetConection;
}
</script>
<button onclick = "index = setChakra(index)" >Click Me!</button>
I think the page is reloading. Add a type attribute with value 'button' to your button.
Like so:
<button type="button" onclick = "index = setChakra(index)" >Click Me!</button>
"<button type=\"button\" onclick=\"getPlanetConection(" + planetIndex + ")\">Click Me!</button>"
This is so that the button acts as a button and not a submit button.

Display the checkboxes selected into a section and the unselected into another one

I want to show the checkboxes selected into a div but actually I have a duplicate item in the list and I'm not sure how to display the unselected items into another div.
You can try out here http://jsfiddle.net/tedjimenez/7wzR5/
Here my code:
JS CODE
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var html = "";
/* Array will be converted to an ul list */
for (var i = 0; i < list.length; i++) {
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").append(html);
THE HTML CODE
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Function to display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "<li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
Simply add another div after selectionResult like this:
<div id="unselectedResult"></div>
And then update showBoxes() with the following code:
function showBoxes(frm) {
var checkedItems = "Checked:<br>\n";
var uncheckedItems = "Unchecked:<br>\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
else {
uncheckedItems = uncheckedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
$('#unselectedResult').append(uncheckedItems);
}
Should get the result you're looking for.
This should work. Added another array listChecked to track checked values.
<script>
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var listChecked = new Array();
$(document).ready(function() {
displayUnchecked();
});
/* Array will be converted to an ul list */
function displayUnchecked()
{
var html = "";
for (var i = 0; i < list.length; i++) {
if ($.inArray(list[i], listChecked) == -1)
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").html(html);
}
</script>
</head>
<body>
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//alert('here');
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
listChecked.push(frm.boxvalue[i].value);
}
}
$.each(listChecked, function (index, value)
{
checkedItems = checkedItems + "<li>" + value + "</li>";
});
//alert('here');
displayUnchecked();
//$("#elmAv").empty();
$("#selectionResult").html(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
</body>

Creating nested tables

Good day. I'm trying to create nested tables one hundred times. However, my code creates one main table and then inside that, there are 100 separate tables. (Thanks to Sir Sachin for the help) What I need is table within a table. Please help me fix the code.
<html>
<head> <title> Hello! </title>
<script type="text/javascript">
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value=1 id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
for(var i=1;i<100;i++) {
var ni = document.getElementById(divIdName);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
var j=i++;
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='" + j + "' id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
}
}
</script>
</head>
<body onload="add()">
<table border="1">
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' />
<div id='myDiv'> </div> </td>
</tr>
</table>
</body>
</html>
This should do it (I have removed the hidden input as it is not needed): http://jsfiddle.net/rPR9w/1/
function add() {
for (i=1; i<=100; i++) {
addAnother(i);
}
}
function addAnother(counter) {
var container = document.getElementById('myDiv' + counter);
container.innerHTML = makeTable(counter + 1);
}
function makeTable(counter) {
return "<table border=1><tr><td> Hello! <div id='myDiv" + counter + "'></td></tr></table>";
}

Categories

Resources