Use the same javascript function in different selects - javascript

I need to use the same JavaScript function called Cerca2 in 3 separated selects. The first one works, but the others do not. I've tried to fix the problem by myself but I can't find where it is.
EDIT: code edited, now work perfectly, tnx for all the suggestion and support guys ^^
This is the html:
<body>
Ricerca per Nome: <input type="text" maxlength="20"/>
<input id="cerca1" type="button" value="Cerca" /><br/><br/>
Ricerca personaggi per Fazione:
<select id="factionSelect">
<option>UNSC</option>
<option>Covenant</option>
<option>Flood</option>
<option>Precursori</option>
</select> <input id="cerca2" selectid="factionSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca armi per tipo:
<select id="weaponSelect">
<option>cinetiche</option>
<option>plasma</option>
<option>energia</option>
</select> <input id="cerca5" selectid="weaponSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca Veicoli per impiego:
<select id="vehicleSelect">
<option>terrestri</option>
<option>volanti</option>
<option>Astronavi</option>
</select> <input id="cerca6" selectid="vehicleSelect" type="button" value="Cerca"/>
<input id="cerca3" type="button" value="Mostra tutto"/>
<input id="cerca4" type="button" value="Ricerca casuale"/><br/><br/>
<hr id="barra"/><br/><p>Risultati ricerca:</p>
<div id="risultati">
<ol id="ricerca">
<li class="vuoto"></li>
</ol>
</div>
</body>
This is the JavaScript:
function Profilo(nom, appar, prof, grup, img){
this.nome = nom;
this.apparizione = appar;
this.profilo = prof;
this.gruppo = grup;
this.immagine = img;
}
function Archivio(){
this.lista = [];
this.inizializza = function(nodo){
var schede = nodo.getElementsByTagName("scheda");
for(var i = 0; i<schede.length; i++){
var categoria = schede[i].getAttribute("categoria");
var nomi = schede[i].getElementsByTagName("nome");
var nome = nomi[0].firstChild.nodeValue;
var apparizioni = schede[i].getElementsByTagName("apparizione");
var apparizione = apparizioni[0].firstChild.nodeValue;
var profili = schede[i].getElementsByTagName("profilo");
var profilo = profili[0].firstChild.nodeValue;
var immagini = schede[i].getElementsByTagName("immagine");
var immagine = immagini[0].firstChild.nodeValue;
var scheda = new Profilo(nome, apparizione, profilo, categoria,immagine);
this.lista.push(scheda);
}
}
this.cerca1 = function(testo){
var risultato = [];
var trovato = 0;
var i = 0;
while(i<this.lista.length && trovato == 0){
if(this.lista[i].nome == testo)
{
trovato = 1;
risultato.push(this.lista[i]);
}
else
i++;
}
if(trovato == 1)
return risultato;
else
{
risultato[0] = null;
return risultato;
}
}
this.cerca2 = function(testo){
var risultati = [];
for(var i = 0; i<this.lista.length; i++){
if(this.lista[i].gruppo == testo)
risultati.push(this.lista[i]);
}
return risultati;
}
this.cerca3 = function(numero){
var risultati = [];
risultati.push(this.lista[numero]);
return risultati;
}
this.genera = function(valori){ // genera la lista con gli elementi di xml
var s = "";
if(valori[0] == null)
s = "Nessun risultato";
else{
for(var i = 0; i<valori.length; i++)
s = s + '<li><span class="trovato" onclick="mostra(this);">' + valori[i].nome + " " + '</span><br/><ol class="nascosto"><li class="nopallino2"> <img src='+ valori[i].immagine+'> <br/><br/>Profilo: '+ valori[i].profilo +'<br/>Apparizione: ' + valori[i].apparizione +'</li></ol></li><br/><br/>';
}
return s;
}
this.nascondi = function(){
var liste = document.getElementsByTagName("ol");
for(var i = 0; i<liste.length; i++){
if(liste[i].className == "nascosto")
liste[i].style.display = "none";
}
}
}
function cercagruppo(){
/*var elenco = document.getElementById("ricerca");
var menu = document.getElementsByTagName("select");
var scelta = menu[0];
var gruppo = scelta.value;
var schede = contenitore.cerca2(gruppo);
elenco.innerHTML = contenitore.genera(schede);
contenitore.nascondi(); */
var elenco = document.getElementById("ricerca");
var menu = document.getElementById(this.getAttribute("selectid"));
var group = menu.value;
var schede = contenitore.cerca2(group);
elenco.innerHTML = contenitore.genera(schede);
contenitore.nascondi();
}
function mostra(nome){
var testo = nome.nextSibling.nextSibling;
if(testo.style.display == "none")
testo.style.display = "block"
else
testo.style.display = "none"
}
// funzione che cerca le schede relative all'oggetto cercato digitando il nome
function cercanome(){
var casella = document.getElementsByTagName("input");
var nome;
var elenco = document.getElementById("ricerca");
var scheda;
nome = casella[0].value;
scheda = contenitore.cerca1(nome);
elenco.innerHTML = contenitore.genera(scheda);
contenitore.nascondi();
}
// funzione per mostrare tutte le schede
function tutto(){
var elenco = document.getElementById("ricerca");
elenco.innerHTML = contenitore.genera(contenitore.lista);
contenitore.nascondi();
}
function generaCasuale(){
var numerogenerato = Math.floor(Math.random()*(parseInt(contenitore.lista.length-1)+1));
if(numerogenerato == randomglobale){
while(numerogenerato == randomglobale)
numerogenerato = Math.floor(Math.random()*(parseInt(contenitore.lista.length-1)+1));
}
randomglobale = numerogenerato;
return numerogenerato;
}
// funzione di ricerca casuale
function casuale(){
var elenco = document.getElementById("ricerca");
var numero = generaCasuale();
var scheda = contenitore.cerca3(numero);
elenco.innerHTML = contenitore.genera(scheda);
contenitore.nascondi();
}
var contenitore = new Archivio();
var randomglobale;
function inizializza(){
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
var c3 = document.getElementById("cerca3");
var c4 = document.getElementById("cerca4");
var c5 = document.getElementById("cerca5");
var c6 = document.getElementById("cerca6");
c1.onclick = cercanome;
c2.onclick = cercagruppo;
c3.onclick = tutto;
c4.onclick = casuale;
c5.onclick = cercagruppo;
c6.onclick = cercagruppo;
var nodo = caricaXML("elenco.xml");
contenitore.inizializza(nodo);
}
window.onload = inizializza;

I'm not sure I totally understand the question, but in this code, c5 and c6 are all getting the cerca2 inputs :
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
var c3 = document.getElementById("cerca3");
var c4 = document.getElementById("cerca4");
var c5 = document.getElementById("cerca2");
var c6 = document.getElementById("cerca2");

In several parts of your code, you select all elements of a certain type, but only use the first such element.
For example:
function cercagruppo(){
...
var menu = document.getElementsByTagName("select"); // gets all "select" elements
var scelta = menu[0]; // gets value of first "select" element
...
}
And also:
function cercanome(){
var casella = document.getElementsByTagName("input"); // gets all "input" elements
...
nome = casella[0].value; // gets value of first "input" element
...
}
If you want to get the values from all select and input elements, you'll need to do so explicitly, such as by looping through the menu and casella arrays instead of selecting only their first items.
Edit: Suggested approach to refactoring code
Having looked at your code a bit more, here's the approach I think you should take:
In your HTML, add an ID attribute to each of your select elements.
Add an attribute to your "cerca2", "cerca5", and "cerca6" input buttons that indicates the ID of the corresponding select element
You can then access the attribute in the cercagruppo() function and use it to select the corresponding select element.
Your cercagruppo() function would look more like this:
function cercagruppo(){
var ol = document.getElementById("ricerca");
var selection = document.getElementById(this.getAttribute("selectid"));
var group = selection.value;
var tabs = contenitore.cerca2(group);
ol.innerHTML = contenitore.genera(tabs);
contenitore.nascondi();
}
Your HTML would end up looking more like this:
Ricerca personaggi per Fazione:
<select id="factionSelect">
<option>UNSC</option>
<option>Covenant</option>
<option>Flood</option>
<option>Precursori</option>
</select> <input id="cerca2" selectid="factionSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca armi per tipo:
<select id="weaponSelect">
<option>cinetiche</option>
<option>plasma</option>
<option>energia</option>
</select> <input id="cerca5" selectid="weaponSelect" type="button" value="Cerca"/>
<br/><br/>
Ricerca Veicoli per impiego:
<select id="vehicleSelect">
<option>terrestri</option>
<option>volanti</option>
<option>Astronavi</option>
</select> <input id="cerca6" selectid="vehicleSelect" type="button" value="Cerca"/>
Edit edit
And of course, you should also fix the error that #mgarant pointed out:
var c1 = document.getElementById("cerca1");
var c2 = document.getElementById("cerca2");
var c3 = document.getElementById("cerca3");
var c4 = document.getElementById("cerca4");
var c5 = document.getElementById("cerca5"); // fixed
var c6 = document.getElementById("cerca6"); // fixed

Related

Manipulation of div elements with javascript

Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.

Counting different input values, add them and show result

I want to make a "drink counter". There are 3 inputs which add another drink onclick. Every drink has a specific value in alcohol (var bier, var wein, var soju).
So on every count up (click), the script is supposed to:
count up the value in the respective input [this works]
add up all the numbers and drinks multiplied by their alcohol value, so added_up = bier_full + soju_full + wein_full;
If you look at the code, you will notice that I'm quite the noob. Help would be much appreciated. I can't think of a way to add all the drinks*alc. values up and display them in the id="status".
HTML:
var full = 100;
var bier = 12.7;
var wein = 10;
var soju = 3.5;
status = document.getElementById("status");
var bier_c = parseInt(document.getElementById("beer").value);
var soju_c = parseInt(document.getElementById("soju").value);
var wein_c = parseInt(document.getElementById("wine").value);
var bier_i = document.getElementById("bier_info");
var soju_i = document.getElementById("soju_info");
var wein_i = document.getElementById("wein_info");
function reset() {
bier_c = 0;
soju_c = 0;
wein_c = 0;
document.getElementById("beer").value = "0";
document.getElementById("soju").value = "0";
document.getElementById("wine").value = "0";
};
function bier_s() {
bier_c++;
document.getElementById("beer").value = bier_c;
bier_full = bier_c * bier;
bier_i.innerHTML = bier_full;
return bier_full;
};
function soju_s() {
soju_c++;
document.getElementById("soju").value = soju_c;
soju_full = soju_c * soju;
soju_i.innerHTML = soju_full;
return soju_full;
};
function wein_s() {
wein_c++;
document.getElementById("wine").value = wein_c;
wein_full = wein_c * wein;
wein_i.innerHTML = wein_full;
return wein_full;
};
added_up = bier_full + soju_full + wein_full;
alert(added_up);
<label>Beer</label><input id="beer" type="button" style="width: 50px;" onclick="bier_s();" value="0">
<label>Soju</label><input id="soju" type="button" style="width: 50px;" onclick="soju_s();" value="0">
<label>Wine</label><input id="wine" type="button" style="width: 50px;" onclick="wein_s();" value="0">
<br/>
<h2 class="c_red" id="status">Let's go!</h2>
<div class="am_info">
<p>Bier: <span id="bier_info"></span></p>
<p>Soju: <span id="soju_info"></span></p>
<p>Wine: <span id="wein_info"></span></p>
</div>
just add a method that runs every time the other methods runs =D
var full = 100;
var bier = 12.7;
var wein = 10;
var soju = 3.5;
var bier_full = 0, soju_full = 0, wein_full = 0;
status = document.getElementById("status");
var bier_c = parseInt(document.getElementById("beer").value);
var soju_c = parseInt(document.getElementById("soju").value);
var wein_c = parseInt(document.getElementById("wine").value);
var bier_i = document.getElementById("bier_info");
var soju_i = document.getElementById("soju_info");
var wein_i = document.getElementById("wein_info");
function reset() {
bier_c = 0;
soju_c = 0;
wein_c = 0;
document.getElementById("beer").value = "0";
document.getElementById("soju").value = "0";
document.getElementById("wine").value = "0";
};
function bier_s() {
bier_c++;
document.getElementById("beer").value = bier_c;
bier_full = bier_c * bier;
bier_i.innerHTML = bier_full;
addUp()
return bier_full;
};
function soju_s() {
soju_c++;
document.getElementById("soju").value = soju_c;
soju_full = soju_c * soju;
soju_i.innerHTML = soju_full;
addUp()
return soju_full;
};
function wein_s() {
wein_c++;
document.getElementById("wine").value = wein_c;
wein_full = wein_c * wein;
wein_i.innerHTML = wein_full;
addUp()
return wein_full;
};
function addUp(){
added_up = bier_full + soju_full + wein_full;
alert(added_up);
}
<label>Beer</label><input id="beer" type="button" style="width: 50px;" onclick="bier_s();" value="0">
<label>Soju</label><input id="soju" type="button" style="width: 50px;" onclick="soju_s();" value="0">
<label>Wine</label><input id="wine" type="button" style="width: 50px;" onclick="wein_s();" value="0">
<br/>
<h2 class="c_red" id="status">Let's go!</h2>
<div class="am_info">
<p>Bier: <span id="bier_info"></span></p>
<p>Soju: <span id="soju_info"></span></p>
<p>Wine: <span id="wein_info"></span></p>
</div>

How to retrieve session storage values and pass it to radio buttons and checkboxes?

As the question is asking, can you get the values from the session storage or local storage to radio buttons on html and the same thing for the checkboxes?
My code:
var customername = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var curcustomer1 = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var lastvist = {"date" : dateall} // only display the date and time
var myJSON = JSON.stringify(customername);
var myJSON1 = JSON.stringify(lastvist); // has the date when the user last has visited
var myJSON2 = JSON.stringify(curcustomer1);
var myJSON3full = JSON.stringify(custinfo);
sessionStorage.setItem("custinfo", myJSON3full);
var objectfull = sessionStorage.getItem("custinfo");
objfull = JSON.parse(objectfull);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
if(object != myJSON) {
sessionStorage.setItem("customername", myJSON);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
var curcustomer = customername;
var myJSONcopy = JSON.stringify(curcustomer);
var object2 = sessionStorage.setItem("curcustomer", myJSONcopy);
var msg5 = "Welcome ";
document.getElementById("customer").innerHTML = msg5 + " " + "New Customer";
document.getElementById("date1").innerHTML = "";
var radiobtn = document.getElementsByName("type");
if(radiobtn.value != 8) {
document.elem.type.value="8";
}
var radiobtn1 = document.getElementsByName("special");
if(radiobtn1.value != 0) {
document.elem.special.value="0";
}
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extras[i].checked = false;
}
}
}
if(object == myJSONcopy) {
radiobtn = document.getElementsByClassName("type").innerHTML = sessionStorage.getItem("type");
radiobtn1 = document.getElementsByClassName("special").innerHTML = sessionStorage.getItem("special");
checboxes = document.getElementsByClassName("extras").innerHTML = sessionStorage.getItem("extras");
}
<td>
<input type="radio" name="type" value="8" checked>Small $8.00
<br>
<input type="radio" name="type" value="10">Medium $10.00
<br>
<input type="radio" name="type" value="15">Large $15.00
<br>
<input type="radio" name="type" value="18">Extra Large $18.00
<br>
<br>
</td>
if you are trying to add the item to multiple buttons that share the same className then you will have to do something like this:
var list = document.getElementsByClassName('type');
var i;
for (i = 0; n < list.length; ++i) {
list[i].value= sessionStorage.getItem('events')
};
But if it's just one button then I will suggest you use getElementById
like this
document.getElementById('Id').value = sessionStorage("events");

Multiple progress bars visualy update only one

i'm working on my JavaScript skills and this is my first program trial here.
Everything was going quite well for me, but i'm stuck on this problem for about 3 days now and i guess there is something i don't get over here.
Well, diving in - i have 2 separate "Training Fields" - each has it's own "Train" button (onclick function) , "Level up" button (onclick function) and progress bar.
The problem is that the higher "Training Field" will progress the lower progress bar and not it's own.
Help will be appreciated! thx
//ignore this line, it's for me for testing
document.getElementById('hideMe').style.visibility = 'hidden';
/*========================================
Javascript for first set
========================================*/
var bodyTotal = 0;
var totalBodyCost = 0;
var bodyCost = 100;
var amountLoaded = 1;
function buyBody(){
bodyCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
if(amountLoaded >= bodyCost){
totalBodyCost += bodyCost;
bodyTotal = bodyTotal + 1;
document.getElementById('bodyTotal').innerHTML = bodyTotal;
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
document.getElementById('bodyCost').innerHTML = nextCost;
document.getElementById("bodyProgressBar").max = nextCost;
bodyCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('bodyProgressBar');
var status = document.getElementById('bodyStatus');
status.innerHTML = al+"/" +bodyCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainBody(){
progressBarSim(amountLoaded);
if(amountLoaded < bodyCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
/*========================================
Javascript for second set
========================================*/
var mindTotal = 0;
var totalMindCost = 0;
var mindCost = 100;
var amountLoaded = 1;
function buyMind(){
mindCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
if(amountLoaded >= mindCost){
totalMindCost += mindCost;
mindTotal = mindTotal + 1;
document.getElementById('mindTotal').innerHTML = mindTotal;
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
document.getElementById('mindCost').innerHTML = nextCost;
document.getElementById("mindProgressBar").max = nextCost;
mindCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('mindProgressBar');
var status = document.getElementById('mindStatus');
status.innerHTML = al+"/" +mindCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainMind(){
progressBarSim(amountLoaded);
if(amountLoaded < mindCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
</head>
<body>
<div style="float:right">
Body Level: <span id="bodyTotal">0</span>
<button onclick="trainBody()">Train Body</button><br>
<progress id="bodyProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="bodyStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="bodyFinalMessage" style="float:left; visibility:hidden" onclick="buyBody()">Body Level Up</button>
<br><br>
Mind Level: <span id="mindTotal">0</span>
<button onclick="trainMind()">Train Mind</button><br>
<progress id="mindProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="mindStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="mindFinalMessage" style="float:left; visibility:hidden" onclick="buyMind()">Mind Level Up</button>
</div>
<div id="hideMe" style="position:absolute; top:400; left:400">
Body Cost: <span id="bodyCost">100</span><br>
Mind Cost: <span id="mindCost">100</span>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
You are reassigning variables and functions using the exact same names amountLoaded, progressBarSim(al).
Because body and mind behavior are very similar you could use a module pattern (http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) to use the same variable and function names within their own scopes.
<button onclick="Body.onClick()">Body</button>
<button onclick="Mind.onClick()">Mind</button>
And in your script file
var Body = (function() {
var me = {};
me.onClick = function() {
console.log("body click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
var Mind = (function() {
var me = {};
me.onClick = function() {
console.log("mind click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
The gotcha here is you can't use body with the inline onclick since that already refers to the body element.

Get value from input fields through an array

I am working on a form where there user can add multiple inputs like:
<script type="text/javascript">
<!--
var counter = 0;
var limit = 4;
window.onload = moreFields;
function moreFields() {
if (counter == limit) {
alert('You have reached the limit of adding ' + counter + ' inputs');
}
else
var newFields = document.getElementById('sa-groep').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var hetId = newField[i].id
if (hetId)
newField[i].id = hetId + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
counter++;
}
This works fine, all input get their unique id, but then i figured out that to catch all the input values it is better through getElementsByClassName
so then i made this to catch the values:
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i] + "<br />");
}
}
the html code is:
<body>
<div id="sa-groep" style="display: none">
<input class="SA" id="sa_" value=" " />
<select class="RC" id="rc_">
<option>Rating</option>
<option value="excellent">Excellent</option>
<option value="good">Good</option>
<option value="ok">OK</option>
</select><br /><br />
<input type="button" value="Remove review"
onclick="this.parentNode.parentNode.removeChild(this.parentNode)" /><br /><br />
</div>
<span id="writeroot"></span>
<input type="button" onclick="moreFields()" value="Give me more fields!" />
<input type="button" onclick="getClassValue()" value="Send form" />
</body>
But the only thing it show is : 3011 contains: So what am i doing wrong?
At first look I suggest you to change document.write (which replace all the text of your document) and instead use console.log("something..") or the property innerHTML in a specific div.
document.write, as I said before, replace all the the page with the string passed.
The problem beside the curly bracket (thanks #James) was the cloning of an hidden fields wich gave an empty result at the first spot in the arrays. To delete the first element of an array i had to delete that with shift() It works, probably it can be better but this is my solution:
function getClassValue() {
var secAut = []; // array met de namen van de secundaire auteurs
var readyItems = document.getElementsByClassName('auteur');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
}
var secAutMinus = secAut.shift(); // 1 element verwijdert uit array ivm dat de eerste input leeg is (display: none)
var relCode = []; // 2e array met de relatiecodes
var relCodeready = document.getElementsByClassName('relcode');
for(var i = 0; i < relCodeready.length; i++){
relCode.push(relCodeready[i].value);
}
var relCodeMinus = relCode.shift(); // 1st element verwijderen
for(var k= 0; k < secAut.length; k++){
console.log(3012+k+ ' contains: ' + secAut[k] + ' is ' + relCode[k] + '<br/>'); // uitlezing arrays minus het eerste lege element
}
}
In this function the loop needs to start from 1 because the 0th element is the hidden (cloned) one.
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for (var i = 1; i < readyItems.length; i++) {
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i - 1] + "<br />");
}
}
There are a couple of other problems, missing curly brace after the else in moreFields.
Here's a working fiddle

Categories

Resources