Local storage wont work with <input> - javascript
I'm currently trying to make something work for in javascript, as u can see i made a Theater hall with javascript.
I made a big table with <input type=checkbox> inside the table data, with generated Id by the loop(which u can see under the if/else in function tekenZaal1().
Now if u press the Load button i want that the checked(pressed) checkboxes will be added to local storage.
I've try some but it won't work, it adds only 1 string to to the local storage with
key: undefined
and
value: undefined.
i've no idea how to fix this what's wrong with my code?
btw: i couldn't get jsfiddle to work with my code idk why but i have a screenshot of my full html and javascript code of the theather hall: http://gyazo.com/a9a3d23ee12e1862e447fab02075446a
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Reserveringspagina</title>
<link type="text/css" rel="stylesheet" href="check.css">
<script type="text/javascript" src="reserveringsjavadeel1.js"></script>
</head>
<body onload="tekenZaal1()">
<div id="content">
</div>
<div id="containergroot">
<div id="content1"></div>
<div id="content2">
</div>
</div>
<button onclick="addStorage()">load</button>
</body>
</html>
javascript:
var zaal1 =
[ //Array van zaal1//
[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0],
[0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,0,0,0],
[0,0,0,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,0,0,0],
[0,0,0,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,0,0,0],
[0,0,0,1,1,1,1,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,1,1,1,1,0,0,0],
[0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,2,2,2,2,2,1,1,1,1,1,0,0],
[0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,2,1,1,1,1,1,0],
[0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,2,1,1,1,1,1,0],
[0,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,2,2,1,1,1,1,0],
[0,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,2,2,1,1,1,1,0],
[0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,2,1,1,1,1,1,0],
[0,1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1,1,0],
[0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,0],
[0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,0,0],
[0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,0,0,0],
[0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0]
];
//Variabelen die worden weergegeven in de <p> die aangemaakt wordt als je op een stoel klikt//
//functie die zaal1 tekent//
function tekenZaal1()
{
var zaal = "";
zaal+="<table border='0' id='tabel'>";
for(i = 0; i < zaal1.length; i++){
zaal+='<tr>';
for (j = 0; j < zaal1[i].length; j++){
if (zaal1[i][j] == 1){
zaal+='<td class="prijslaag"><input title="rij'+(i+1)+'stoel'+j+'" type="checkbox" class="stoel1" id="rij'+i+'stoel'+j+'" name="choice" value="7,50" onchange="bereken(1 , checked, Blauw)"></td>';
}
else if (zaal1[i][j] == 2){
zaal+='<td class="prijsmiddel"><input title="rij'+(i+1)+'stoel'+j+'" type="checkbox" class="stoel2" id="rij'+i+'stoel'+j+'" name="choice" value="9" onchange="bereken(2, checked, Oranje)"></td>';
}
else if (zaal1[i][j] == 3){
zaal+='<td class="prijshoog"><input title="rij'+(i+1)+'stoel'+j+'" type="checkbox" class="stoel3 "id="rij'+i+'stoel'+j+'" name="choice" value="11" onchange="bereken(3 , checked, Rood)"></td>';
}
else {
zaal+='<td><img src="witlogo.png" width="40" height="40"></td>';
}
}
zaal+="</tr>";
}
zaal+="</table><br>";
document.getElementById("content").innerHTML+= zaal;
}
function bereken(type, checked, kleur) {
if (checked) {
if (type == 1) {
prijs += 7.50;
}
else if (type == 2) {
prijs += 9;
}
else if (type == 3) {
prijs += 11;
}
//Maakt een <p> en zet daar de aangeklikte stoel in//
var para = document.createElement('p');
para.id = ('stoel'+ type);
var node = document.createTextNode(kleur);
para.appendChild(node);
var element = document.getElementById("content1");
element.appendChild(para);
}
else {
if (type == 1) {
prijs -= 7.50;
}
else if (type == 2) {
prijs -= 9;
}
else if (type == 3) {
prijs -= 11;
}
// Verwijderd de desbetreffende <p>stoel die is aangemaakt//
para = document.getElementById('stoel'+type);
para.parentElement.removeChild(para);
}
document.getElementById("content2").innerHTML = "<p id='prijstotaal'>\u20ac"+" "+prijs+"</p>";
}
function addStorage() {
var stoelen = ['rij'+i+"stoel"+j+""]
var zaal = ['zaal1', 'zaal2', 'zaal3']
if ("localStorage" in window) {
localStorage.setItem(stoelen.value, zaal.value);
alert("localstorage set");
}
else {
alert("no localStorage in window");
}
}
Related
I can't figure out my JavaScript function is not working
I have to create a game where the user has to guess a number, for that I call a JavaScript function on an external file which is activated when the button is clicked. My HTML: ` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Devoir JavaScript</title> </head> <body> <p>Vous devez trouver un nombre compris entre 1 et 100 !</p> <form name="myForm" method="POST"></form> Nombre : <input type="text" name="nombre" value="" /> <input type="button" onclick="return verif()" value="Jouer" /> </form> <script type="text/javascript" src="script.js"></script> </body> </html> ` My JavaScript: var numero = Math.floor(Math.random() * 100) + 1; var essai = 0; function verif() { essai++; var choix = document.forms["myForm"]["choix"].value; if (choix == null || choix == "") { alert("Indiquer un nombre !"); return false; } if (choix < numero) { alert = "Le nombre indiquer est trop petit !"; return false; } if (choix > numero) { alert = "Le nombre indiquer est trop grand !"; return false; } if (choix == numero) { alert = "Bravo vous avez trouver en " + essai + "essais !"; return true; } } I have checked the name of my files and their extentions so as not to make a mistake. I don't understand or I made a mistake. PS: I am new to JavaScript. I have been looking since yesterday so thank you for your help.
I tried running your code and inside Console it says the value could not be read. I slightly changed your Javascript code and it worked. //var choix = document.forms["myForm"]["choix"].value; code before var choix = document.getElementsByName("nombre").value; //after changed When using Javascript if your code is not running, you should press F12 and look at the Console to see what your code is failing. This is the full code that I changed: var numero = Math.floor(Math.random() * 100) + 1; var essai = 0; function verif() { essai++; var choix = document.getElementsByName("choix").value; document.write(choix); if (choix == null || choix == "") { alert("Indiquer un nombre !"); return false; } if (choix < numero) { alert = "Le nombre indiquer est trop petit !"; return false; } if (choix > numero) { alert = "Le nombre indiquer est trop grand !"; return false; } if (choix == numero) { alert = "Bravo vous avez trouver en " + essai + "essais !"; return true; } } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Devoir JavaScript</title> </head> <body> <p>Vous devez trouver un nombre compris entre 1 et 100 !</p> <form name="myForm" method="POST"></form> Nombre : <input type="number" name="choix" value=""/> <input type="button" onclick="return verif()" value="Jouer" /> </form> </body> </html>
Your error says that you are accessing the property value from undefined. There is no "choix" in your HTML. You can use indices to get your particular element value: var choix = document.forms[0].elements[0].value; Or keeping the same approach as yours, I can use the correct field "nombre" : var choix = document.forms["myForm"]["nombre"].value;
I need to update a specific cell in an html table using only javascript, how do i target this cell?
So for an assignment I need to create a working shopping cart with remove function and if an article is already in the cart It should update the existing data when added again. For instance I have the following cart. Name: Quantity: Price: Total: Potato 1 1 1 This cart has been created as a table. So If I select another potato from a dropdown list it should update the current potato in the cart so the quantity becomes 2 and the total becomes 2. I have been looking for an answer to this problem for 4 hours now and I just can't seem to get any closer to the solution. current code that adds items to the table: "use strict"; const btn = document.getElementById('toevoegen'); const keuzeLijst = document.getElementById('groente'); const aantalArt = document.getElementById('aantal'); leesGroenten(); //leest de JSON file in async function leesGroenten() { const response = await fetch("groenten.json") if (response.ok) { const groenten = await response.json(); console.log(groenten); verwerkGroenten(groenten); } else { console.log("oeps er ging iets mis!"); } }; //Verwerkt de JSON file function verwerkGroenten(groenten) { for (const groente of groenten) { voegGroentenToeAanLijst(groente); } }; //Voegt de JSON file objecten toe aan de groente lijst function voegGroentenToeAanLijst(groente) { let keuzeGroente = document.createElement("option"); keuzeGroente.dataset.naam = groente.naam; keuzeGroente.dataset.prijs = groente.prijs; keuzeGroente.dataset.eenheid = groente.eenheid; keuzeGroente.dataset.aantal = 1; keuzeGroente.innerText = groente.naam + '(' + `${groente.prijs}` + "/" + `${groente.eenheid}` + ')'; keuzeLijst.appendChild(keuzeGroente); } btn.onclick = controleLijst; function controleLijst() { if (aantalArt.value === '' || aantalArt.value < 1) { document.getElementById('foutMelding').hidden = false; } else { document.getElementById('foutMelding').hidden = true; const groenteNaam = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam; let gevondenListItem = vindListItemMetNaam(groenteNaam); if (gevondenListItem === null) { voegGroenteToeAanMandje(groenteNaam) } else { //Niet gevonden hoe ik cellen moet updaten voegGroenteToeAanMandje(groenteNaam) updateListItem(gevondenListItem) } } } //Deze functie zoekt doorheen de tabel naar een artikel met de zelfde naam als het arikel //uit de keuze lijst. function vindListItemMetNaam(groenteNaam) { const groenteNamen = document.querySelectorAll("tr"); for (const groente of groenteNamen) { if (groente.id === groenteNaam) { return groente; } } return null; } //Deze functie zorgt dat een bestaand artikel wordt geupdate function updateListItem() { console.log("bestaal al"); } // Na een geslaagde controle wordt het artikel toegevoegd aan de tabel via onderstaande code function voegGroenteToeAanMandje() { const tbody = document.querySelector('tbody'); tbody.id = 'tabel' const tr = tbody.insertRow(); tr.id = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam const tdNaam = tr.insertCell(); tdNaam.id = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam tdNaam.innerText = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam; const tdAantal = tr.insertCell(); tdAantal.innerText = 1; tdAantal.id = 'aantal'; const tdPrijs = tr.insertCell(); tdPrijs.innerText = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.prijs; tdPrijs.id = 'prijs' const tdTeBetalen = tr.insertCell(); tdTeBetalen.innerText = tdPrijs.innerText; tdTeBetalen.id = 'te betalen'; const verwijderTd = tr.insertCell(); const verwijderHyperlink = document.createElement("img"); verwijderHyperlink.src = "vuilbak.png" verwijderTd.appendChild(verwijderHyperlink); verwijderHyperlink.onclick = function () { const tr = this.parentElement.parentElement; tr.remove(); } }; and the html as requested <!DOCTYPE html> <html lang="nl"> <head> <link rel="icon" href="javascript.ico" type="image/x-icon"> <title>Groentenwinkel</title> <link rel="icon" href="groentenwinkel.ico" type="image/x-icon"> <link rel="stylesheet" href="groentenwinkel.css" /> <script src="groentenwinkel.js" defer></script> </head> <body> <img src="banner.jpg" id="banner" alt="banner"> <h1>Bestelling</h1> <label>Groente: <select id="groente"> <option value="">--- maak uw keuze ---</option> </select> </label> <label>Aantal: <input id="aantal"> </label> <button id="toevoegen">Toevoegen aan mandje</button> <button id="test">testknopje</button> <table> <thead> <tr> <th>Groente</th> <th>Aantal</th> <th>Prijs</th> <th>Te Betalen</th> <th> </th> </tr> </thead> <tbody> </tbody> </table> <div id="fout" hidden class="fout">Fout! Kies groente en aantal (minstens 1).</div> </body> </html> I have a function that checks if the selected item from the drop down list already appears in the table. But I have no idea how I can call a specific cell from a table to check this. Lets say I choose potato I then want to check if there is already an item in my table with the name potato and if so I want to update the quantity and total of that item. Is this even possible?
Since you set an unique ID (I hope) for TR, you can simply check it's existence and update it if already exists: "use strict"; const btn = document.getElementById('toevoegen'); const keuzeLijst = document.getElementById('groente'); const aantalArt = document.getElementById('aantal'); leesGroenten(); //leest de JSON file in async function leesGroenten() { /* changed */ // const response = await fetch("groenten.json") /* start temporary .json */ const response = { ok: true, json: async () => { return [{ naam: "naam 1", prijs: "prijs 1", eenheid : "eenheid 1" }, { naam: "naam 2", prijs: "prijs 2", eenheid : "eenheid 2" }] } } /* end temporary .json */ if (response.ok) { const groenten = await response.json(); console.log(groenten); verwerkGroenten(groenten); } else { console.log("oeps er ging iets mis!"); } }; //Verwerkt de JSON file function verwerkGroenten(groenten) { for (const groente of groenten) { voegGroentenToeAanLijst(groente); } }; //Voegt de JSON file objecten toe aan de groente lijst function voegGroentenToeAanLijst(groente) { let keuzeGroente = document.createElement("option"); keuzeGroente.dataset.naam = groente.naam; keuzeGroente.dataset.prijs = groente.prijs; keuzeGroente.dataset.eenheid = groente.eenheid; keuzeGroente.dataset.aantal = 1; keuzeGroente.innerText = groente.naam + '(' + `${groente.prijs}` + "/" + `${groente.eenheid}` + ')'; keuzeLijst.appendChild(keuzeGroente); } btn.onclick = controleLijst; function controleLijst() { if (aantalArt.value === '' || aantalArt.value < 1) { document.getElementById('foutMelding').hidden = false; } else { document.getElementById('foutMelding').hidden = true; const groenteNaam = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam; let gevondenListItem = vindListItemMetNaam(groenteNaam); if (gevondenListItem === null) { voegGroenteToeAanMandje(groenteNaam) } else { //Niet gevonden hoe ik cellen moet updaten voegGroenteToeAanMandje(groenteNaam) updateListItem(gevondenListItem) } } } //Deze functie zoekt doorheen de tabel naar een artikel met de zelfde naam als het arikel //uit de keuze lijst. function vindListItemMetNaam(groenteNaam) { const groenteNamen = document.querySelectorAll("tr"); for (const groente of groenteNamen) { if (groente.id === groenteNaam) { return groente; } } return null; } //Deze functie zorgt dat een bestaand artikel wordt geupdate function updateListItem() { console.log("bestaal al"); } // Na een geslaagde controle wordt het artikel toegevoegd aan de tabel via onderstaande code function voegGroenteToeAanMandje() { /* changed */ const tbody = document.getElementById("tabel"); /* id is set in HTML already */ // tbody.id = 'tabel' /* check if TR with this id already exists */ const exist = document.getElementById(keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam); /* set tr to already existed row or if it doesn't exist insert a new one */ const tr = exist || tbody.insertRow(); tr.id = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam; /* this will be used to check existance of columns, this method is shorter than alternative: if (exist) ... else ... */ var child = 0; /* get existing cell or insert new one */ const tdNaam = tr.children[child++] || tr.insertCell(); /* do you really need an ID here? */ // tdNaam.id = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam tdNaam.innerText = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.naam; const tdAantal = tr.children[child++] || tr.insertCell(); tdAantal.innerText = 1; /* don't use same IDs on multiple elements */ // tdAantal.id = 'aantal'; const tdPrijs = tr.children[child++] || tr.insertCell(); tdPrijs.innerText = keuzeLijst.options[keuzeLijst.selectedIndex].dataset.prijs; /* don't use same IDs on multiple elements */ // tdPrijs.id = 'prijs' const tdTeBetalen = tr.children[child++] || tr.insertCell(); tdTeBetalen.innerText = tdPrijs.innerText; /* don't use same IDs on multiple elements */ // tdTeBetalen.id = 'te betalen'; /* since this is "static" cell, we don't need update it if it's already exists */ if (!exist) { const verwijderTd = tr.insertCell(); const verwijderHyperlink = document.createElement("img"); verwijderHyperlink.src = "vuilbak.png" verwijderTd.appendChild(verwijderHyperlink); verwijderHyperlink.onclick = function () { const tr = this.parentElement.parentElement; tr.remove(); } } }; <!DOCTYPE html> <html lang="nl"> <head> <link rel="icon" href="javascript.ico" type="image/x-icon"> <title>Groentenwinkel</title> <link rel="icon" href="groentenwinkel.ico" type="image/x-icon"> <link rel="stylesheet" href="groentenwinkel.css" /> <script src="groentenwinkel.js" defer></script> </head> <body> <img src="banner.jpg" id="banner" alt="banner"> <h1>Bestelling</h1> <label>Groente: <select id="groente"> <option value="">--- maak uw keuze ---</option> </select> </label> <label>Aantal: <input id="aantal"> </label> <button id="toevoegen">Toevoegen aan mandje</button> <button id="test">testknopje</button> <table id="tabel"> <thead> <tr> <th>Groente</th> <th>Aantal</th> <th>Prijs</th> <th>Te Betalen</th> <th> </th> </tr> </thead> <tbody> </tbody> </table> <div id="fout" hidden class="fout">Fout! Kies groente en aantal (minstens 1).</div> <!-- added start --> <div id="foutMelding">No clue what this is for</div> <!-- added end --> </body> </html> I've added /* comments */ through out the code. P.S. Since you are asking in english, next time please provide code in english, it's very difficult read and understand your code.
Javascript textcontent is not displaying anything
I am trying to create the below game. The Javascript textcontent however is not displaying anything. The Computer selects a random "secret" number between some min and max. The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number. Extra challenges: Limit the number of guesses the Player has. Keep track/report which numbers have been guessed. My code is as follows: const submitguess = document.querySelector('.submitguess'); const inputno = document.querySelector('#secretno'); const resultmatch = document.querySelector('#resultmatch'); const highorlow = document.querySelector('#highorlow'); const guesslist = document.querySelector('#guesslist'); let randomNumber = Math.floor(Math.random() * 10) + 1; let count = 1; let resetButton; function guessvalid() { let input = Number(inputno.value); //alert('I am at 0'); if (count === 1) { guesslist.textContent = 'Last guesses:'; } guesslist.textContent += input + ', '; if (randomNumber === input) { //alert('I am here 1'); resultmatch.textContent = 'Bazingaa!!! You got it absolutely right'; highorlow.textContent = ''; guesslist.textContent = ''; GameOver(); } else if (count === 5) { resultmatch.textContent = 'Game Over !! Thanks for playing.'; //alert('I am here 2'); highorlow.textContent = ''; guesslist.textContent = ''; GameOver(); } else { //alert('I am here 3'); resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!'; if (randomNumber > input) { //alert('I am here 4'); highorlow.textContent = 'Hint.The guess was lower than the secret no.'; } else if (randomNumber < input) { //alert('I am here 5'); highorlow.textContent = 'Hint.The guess was higher than the secret no.'; } } count = count + 1; input.value = ''; } submitguess.addEventListener('click', guessvalid); function GameOver() { inputno.disabled = true; submitguess.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Lets play again'; document.body.appendChild(resetButton); resetButton.addEventListener('click', reset); } function reset() { count = 1; const newDisplay = document.querySelectorAll('.display p'); for(let k = 0 ; k < newDisplay.length ; k++) { newDisplay[k].textContent = ''; } resetButton.parentNode.removeChild(resetButton); inputno.disabled = false; submitguess.disabled = false; inputno.value = ''; randomNumber = Math.floor(Math.random() * 10) + 1; } <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Hi Low</title> <link rel='stylesheet' href='style.css'> </head> <body> <header> <h3>Lets guess the secret number between 1 and 10</h3> <h4>You have 5 chances to guess </h4> </header> <br/> <br/> <form class='form'> <div class='secretno'> <label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label> <input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required> <span class='validity'></span> <input type='button' class='submitguess' value='submit'> </div> </form> <br/> <br/> <div class='display'> <p id='resultmatch'> </p> <p id='highorlow'> </p> <p id='guesslist'> </p> </div>
Because I don't have enough contribution I have to write as an answer. First is here <input type='submit' class='submitguess'> you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button" Second const resetParas = document.querySelectorAll('.display p'); You should check this one. resetParas set but you check display length.
Javascript,Jquery:How to add and delete elem autoly with CheckBox in one div,and elem displays in another div with javascript
I have two divs. One has three elems(John,Snow,Stock).Before each elem,there is a checkbox.Once John is checked,it will display in staff div.When John is unchecked,It is gone. When elems is checked to add_sub(e), it works fine. Once unchecked, it failed which is displays Nana. My div code : <div id="role_div"> <table > <td style="word-break:break-all;"><input type="checkbox" name="uId" value="John">John</td> <td style="word-break:break-all;"><input type="checkbox" name="uId" value="Snow">Snow</td> <td style="word-break:break-all;"><input type="checkbox" name="uId" value="Stock">Stock</td> </table> </div> <div id="staff" onclick="this.focus();"></div> my js code: var staff = document.getElementById("staff"); function add_sub(el) { if (el.checked){ currNum += el.value+'<br />'; } else { currNum -= el.value+'<br />'; } staff.value = currNum; } form.addEventListener("click", function(ev){ if(ev.target.getAttribute("type") == "checkbox"){ add_sub(ev.target); } },false); } ` My code is not the best way.Who can help me ?
I hava solved this problem; var currNum="" ; var selected_staff = document.getElementById("selected_staff"); //var form = document.getElementById("transmit_form"); function add_sub(el) { if (el.checked) { //alert(el.value); selected_staff.innerHTML += el.value+'<br />'; // selected_staff.innerHTML=currNum; selectedStaff.value = selected_staff.innerHTML; alert(selectedStaff.value); } else { // currNum -= el.value; var strReplace = el.value+'<br>'; //alert(strReplace); selected_staff.innerHTML = selected_staff.innerHTML.replace(new RegExp(strReplace,"g"),""); selectedStaff.value = selected_staff.innerHTML; alert(selectedStaff.value); } } staff_div.addEventListener("click", function(ev){ if(ev.target.getAttribute("type") == "checkbox"){ add_sub(ev.target); } },false);
When making a tic tac toe game in javascript, how can you create an A.I. that will select any random box, but one that hasn't been chosen?
I'm making a tic-tac-toe game, and I'm stuck. I sort of made an A.I. that moves after you but it's all a bit messed up. Try it yourself and see what happens. Can anybody have a look and see if they're able to improve it and explain how they did it? And to make things simple, how could I make the A.I. choose any box which hasn't been chosen yet. Here's the code: <!DOCTYPE html> <html> <body> <input type="button" id="k1" value=" " onclick="tictactoe(this)"> <input type="button" id="k2" value=" " onclick="tictactoe(this)"> <input type="button" id="k3" value=" " onclick="tictactoe(this)"> <br /> <input type="button" id="k4" value=" " onclick="tictactoe(this)"> <input type="button" id="k5" value=" " onclick="tictactoe(this)"> <input type="button" id="k6" value=" " onclick="tictactoe(this)"> <br /> <input type="button" id="k7" value=" " onclick="tictactoe(this)"> <input type="button" id="k8" value=" " onclick="tictactoe(this)"> <input type="button" id="k9" value=" " onclick="tictactoe(this)"> <script> var Xturn = true; var nummoves = 0; var cat; function tictactoe(square) { var value = square.value; var doc1 = document.getElementById("k1").value; var doc2 = document.getElementById("k2").value; var doc3 = document.getElementById("k3").value; var doc4 = document.getElementById("k4").value; var doc5 = document.getElementById("k5").value; var doc6 = document.getElementById("k6").value; var doc7 = document.getElementById("k7").value; var doc8 = document.getElementById("k8").value; var doc9 = document.getElementById("k9").value; for (nummoves = 0; nummoves < 2; nummoves++) { if (doc1 == "X") { cat = document.getElementById("k2").value = "O"; Xturn = true; } if (doc2 = "X") { cat = document.getElementById("k4").value = "O"; Xturn = true; } if (doc3 == "X") { cat = document.getElementById("k5").value = "O"; Xturn = true; } if (doc4 == "X") { car = document.getElementById("k9").value = "O"; } } for (nummoves = 2; nummoves < 3; nummoves++) { if (doc1 == "X") { cat = document.getElementById("k7").value = "O"; Xturn = true; } } if (value != "X" && value != "O") { if (Xturn == true) { square.value = "X"; return Xturn = false; nummoves++; } else if (Xturn == false) { square.value = "O"; return Xturn = true; nummoves++; } } else { alert("That square has been clicked."); } } </script> </body> </html> Note the whole concept isn't mine I admit, but i did kind of it the A.O. part which is slightly messed up.
Keep track of a list of open squares, and just randomly select from that list. That way you can eliminate the loop.
You can iterate thought the "buttons" and take the first that is not checked, or another one, based on random. for(i=1;i<10;i++) { if (document.getElementById('k'+i).value = ' ') { // not played yet ! } }
Consider the following logic: // function that does an AI move function doAIMove(xOrO) { // randomly gets a number from 1 to 9 var randomSquare = document.getElementById("k" + getRandomInt(1, 9)); while (randomSquare.value != " ") { randomSquare = document.getElementById("k" + getRandomInt(1, 9)); } randomSquare.value(xOrO); } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } That is not efficient, but it works as you asked. Anyway, you need to check if there's still remaining squares to fill in. You should also consider implementing "the" tic tac toe AI, which is very simple. You should follow this pseudo algorithm for so: When making a tic-tac-like game, the AI should work like this: 1. Check if there is a tile that you can win in 1 move if there is no such tile: 2. Check if there is a tile that your opponent can win in 1 move if there is no such tile: 3. Check if there is a tile that can make two tiles apply to the rule #1 if there is no such tile: 4. Check if there is a tile that your opponent can make two tiles apply to the rule #2 if there is no such tile: 5. implement your own AI form this point
jsFiddle link for the HTML and JS/JQuery implementation for Tic-Tac-Toe. Currently its only a two player implementation without computer as opponent. Hope you can build on top of it. <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title> - jsFiddle demo by bhatkrishnakishor</title> <script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <style type='text/css'> .tictactoe { width: 125px; height: 125px; background: #A2A8A1; }; </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ //this is a demo tic tac toe game $(document).ready($('input.tictactoe').click(tictactoe)); $(document).ready($('#ff').click(reset)); var whoseMove = 'X'; var xMove = new Array(); var oMove = new Array(); var gameOver = false; var winningConditions = new Array( 'aa/ab/ac','ba/bb/bc','ca/cb/cc','aa/ba/ca','ab/bb/cb','ac/bc/cc','aa/bb/cc','ac/bb/ca'); var whoWon = ''; function tictactoe() { if(gameOver == false && this.value == ' '){ if(whoseMove == 'X'){ this.value = whoseMove; xMove[xMove.length] = this.id; whoseMove = 'O'; } else { this.value = whoseMove; oMove[oMove.length] = this.id; whoseMove = 'X'; } } if(xMove.length >2){ whoWon = endGame(); } if(gameOver && whoWon != '' && whoWon != 'draw') { alert(whoWon + ' won!') } if(!gameOver && whoWon == 'draw') { alert('Games been draw!'); } } function endGame() { var winningCombinations = new Array(); //set this variable value to true incase the game is over gameOver = true; for(var index = 0; index < 8; index = index + 1){ var xMatchCount = 0; var oMatchCount = 0; winningCombinations = winningConditions[index].split('/'); for(var i = 0; i < 3; i = i + 1){ console.log('winningCombinations ' + winningCombinations[i]); for(var j = 0; j < xMove.length; j = j + 1){ console.log('xMove ' + xMove[j]); if(winningCombinations[i] == xMove[j]){ xMatchCount = xMatchCount + 1; if(xMatchCount == 3){ return 'X'; } } } for(var k = 0; k < oMove.length; k = k + 1){ //console.log('oMove ' + oMove[k]); if(winningCombinations[i] == oMove[k]){ oMatchCount = oMatchCount + 1; if(oMatchCount == 3){ return 'O'; } } } } } console.log('x Move Count ' + xMove.length); console.log('o Move Count ' + oMove.length); if(xMatchCount < 3 && oMatchCount < 3){ gameOver = false; } if(xMove.length + oMove.length == 9){ return 'draw'; } } function reset() { console.log('Xs Move - ' + xMove.join('/')); console.log('Os Move - ' + oMove.join('/')); console.log(winningConditions.length); whoseMove = 'X'; xMove = new Array(); oMove = new Array(); gameOver = false; whoWon = ''; $('input').filter(function() { if(this.id != 'ff') { this.value = ' '; } }); } });//]]> </script> </head> <body> <input type="button" id="aa" class="tictactoe" value=" "> <input type="button" id="ab" class="tictactoe" value=" "> <input type="button" id="ac" class="tictactoe" value=" "> <br /> <input type="button" id="ba" class="tictactoe" value=" "> <input type="button" id="bb" class="tictactoe" value=" "> <input type="button" id="bc" class="tictactoe" value=" "> <br /> <input type="button" id="ca" class="tictactoe" value=" "> <input type="button" id="cb" class="tictactoe" value=" "> <input type="button" id="cc" class="tictactoe" value=" "> <br /><br /> <input type="button" id="ff" value="Reset"> </body>