Tic-Tac-Toe Loop - javascript

I am making a game of tic-tac toe in javascript. I have laid out some of what I believe to be the basic building blocks:
var board = [
0, 0, 0,
0, 0, 0,
0, 0, 0
];
gameOn = true;
player1Move = true;
counter = 0;
player1 = [];
player2 = [];
var ask = console.log(prompt('where would you like to go?'));
var drawBoard = function(){
console.log(" A " + (board[0]) + "| B " + (board[1]) + "| C " + (board[2]));
console.log(" ------------- ");
console.log(" D " + (board[3]) + "| E " + (board[4]) + "| F " + (board[5]));
console.log(" ------------- ");
console.log(" G " + (board[6]) + "| H " + (board[7]) + "| I " + (board[8]));
console.log(" ------------- ");
};
var solutions = [
(board[0] && board[1] && board[2]) || (board[3] && board[4] && board[5]) ||
(board[6] && board[7] && board[8]) || (board[0] && board[3] && board[6]) ||
(board[1] && board[4] && board[7]) || (board[2] && board[5] && board[8]) ||
(board[0] && board[4] && board[8]) || (board[2] && board[4] && board[6])
];
while (gameOn === true){
// for loop for game logic
for (var i = 0 ; i < 9; i++){
if (player1Move === true) {
player1.push(ask);
drawBoard();
player1Move = false;
} else if (player1Move === false){
player2.push(ask);
drawBoard();
player1Move = true;
} else if ((player1 || player2) === solutions){
gameOn = false;
console.log((player1 || player2) + "wins!");
} else {
gameOn = false;
console.log("Tie Game!");
}
}
}
I know that the syntax of my main loop is incorrect. Why can't I do what is currently written? If you had this existing code, what type of loop setup would you use to accomplish this? Sorry if this seems not specific enough, I am just lost in the logic of it all!
With this existing loop all I am trying to do is go through and prompt the 2 users 9 times(because maximum moves = 9) in total for now. Once that works than I will keep adding more game logic into it. Why can't I get the prompt to come up 9 times? The current result is that it prompts me once, prints out the board 9 times and false after all of it.
This just needs to work in a terminal window for now too by the way.

I changed your code as little as possible, but a few things are different, which I am explaining bit by bit.
var board = {
A: null,
B: null,
C: null,
D: null,
E: null,
F: null,
G: null,
H: null,
I: null
};
gameOn = true;
player1Move = true;
var drawBoard = function(){
console.log(" A " + (board.A || '') + "| B " + (board.B || '') + "| C " + (board.C || ''));
console.log(" ------------- ");
console.log(" D " + (board.D || '') + "| E " + (board.E || '') + "| F " + (board.F || ''));
console.log(" ------------- ");
console.log(" G " + (board.G || '') + "| H " + (board.H || '') + "| I " + (board.I || ''));
console.log(" ------------- ");
};
var solutions = function() {
return (board.A && (board.A == board.B && board.A == board.C))
|| (board.D && (board.D == board.E && board.D == board.F))
|| (board.G && (board.G == board.H && board.G == board.I));
};
drawBoard();
var currentPlayer;
while (gameOn === true){
// for loop for game logic
for (var i = 0 ; i < 9; i++){
if (solutions()){
console.log(currentPlayer + " wins!");
gameOn = false;
break;
}
//else {
// gameOn = false;
// console.log("Tie Game!");
//}
currentPlayer = 'Player 1';
if(!player1Move)
currentPlayer = 'Player 2';
var ask = prompt(currentPlayer + ': where would you like to go (A or B or C or ..)?');
if(ask == 'exit') {
gameOn = false;
break;
}
if (player1Move === true) {
//player1.push(ask);
board[ask] = 'X';
drawBoard();
player1Move = false;
} else if (player1Move === false){
board[ask] = 'O';
drawBoard();
player1Move = true;
}
}
}
It's not completely finished, but then that's something you can do afterwards, and probably you didn't want me to do it all for you.
This all works in a Chrome console.
There were a couple of basic things that were holding you back:
var ask = console.log(prompt('where would you like to go?')); should be var ask = prompt(currentPlayer + ': where would you like to go?'); - your version was filling ask with null.
This prompt was also in the wrong place: it needs to be in the loop, and after drawBoard(), so that the player has something to look at.
I've changed the board from an array into an object, so that player answers like 'A' refer directly to the object fields. And that way the player arrays could be removed.
The solutions() function needs completing, as you can see, and there may be a neater way of doing this.
I added the possibility of writing 'exit' in the prompt, otherwise there's no way of exiting the game early.
I didn't finish the 'Tie game!' code.

Make sure you understand the global object is, and what window.prompt is, and what console.log is in your context. It is absolutely necessary to get to know a debugger for your environment. In Chrome it's called Developer Tools.
window.prompt is not very useful in code sandboxes like jsfiddle, or the Stack overflow bulit-in ones. I suggest using HTML for your user interface.
function init() {
trapForm();
trapInput();
toggleCurrentUser();
askUser();
}
var game = [
[null,null,null],
[null,null,null],
[null,null,null]
];
var trapInput = function() {
// capture input and use to to create a play in the game
document.querySelector('#go').addEventListener('click',function(ev) {
var position = document.querySelector('#square').valueAsNumber;
if (position < 10 && position > 0) {
// render X or O to the HTML
var td = document.querySelectorAll('#t3 td')[position-1];
td.innerHTML = currentUser;
// modify the corresponding game array
var row = Math.floor( (position-1) / 3 );
var col = ( (position+2) % 3) ;
game[row][col] = currentUser;
// this helps us visualize what's happening
debug(game);
checkGameStatus();
toggleCurrentUser();
} else {
debug({"msg":"illegal move"});
}
});
};
var trapForm = function() {
// prevent form from submitting
var f = document.querySelector('#f');
f.addEventListener('submit',function(ev) {
ev.preventDefault();
trapInput();
});
};
;(function(window,document,undefined){
"use strict";
function init() {
trapForm();
trapInput();
toggleCurrentUser();
askUser();
}
var currentUser = 'Y';
var toggleCurrentUser = function(){
if (currentUser === 'X') {
currentUser = 'Y';
} else {
currentUser = 'X';
}
document.querySelector('#currentuser').value = currentUser;
};
var isVirginal = function(game) {
return game.every(function(row) {
return row.every(function(cell) { return (cell === null); });
});
};
var isStaleMate = function(game){
return game.every(function(row){
return row.every(function(cell){
return (cell === 'X' || cell === 'Y');
});
});
};
var horizontalWinner = function(game) {
var r = false;
return game.some(function(row){
var firstletter = row[0];
if (firstletter === null) {
return false;
} else {
return row.every(function(cell){
return ( cell !== null && cell === firstletter);
});
}
});
};
var verticalWinner = function(game) {
var r = false;
for (var i = 0; i < 4; i++) {
if (game[0][i] === null) {
continue;
}
if (game[0][i] === game[1][i] && game[1][i] === game[2][i]) {
r = game[0][i];
break;
}
};
return r;
};
var diagonalWinner = function(game) {
var r = false;
if (game[0][0] !== null && (game[0][0] === game[1][1] === game[2][2])) {
r = game[0][0];
}
if (game[0][2] !== null && (game[0][2] === game[1][1] === game[2][0])) {
r = game[0][2];
}
return r;
};
var checkGameStatus = function(){
var r = 'unknown';
if (isVirginal(game)) {
r = 'Virginal Game';
} else {
r = 'In Play';
}
if (isStaleMate(game)) {
r = 'Stale Mate';
}
if (diagonalWinner(game)){
r = 'Diagonal Winner: ' + diagonalWinner(game);
}
if (verticalWinner(game)) {
r = 'vertical Winner: ' + verticalWinner(game);
}
if (horizontalWinner(game)) {
r = 'Horizontal Winner: ' + horizontalWinner(game);
}
document.querySelector('#status').value = r;
};
var debug = function(stuff) {
document.querySelector('#debug').innerHTML = JSON.stringify(stuff);
};
var game = [
[null,null,null],
[null,null,null],
[null,null,null]
];
var trapInput = function() {
// capture input and use to to create a play in the game
document.querySelector('#go').addEventListener('click',function(ev) {
var position = document.querySelector('#square').valueAsNumber;
if (position < 10 && position > 0) {
// render X or O to the HTML
var td = document.querySelectorAll('#t3 td')[position-1];
td.innerHTML = currentUser;
// modify the corresponding game array
var row = Math.floor( (position-1) / 3 );
var col = ( (position+2) % 3) ;
game[row][col] = currentUser;
// this helps us visualize what's happening
debug(game);
checkGameStatus();
toggleCurrentUser();
} else {
debug({"msg":"illegal move"});
}
});
};
var trapForm = function() {
// prevent form from submitting
var f = document.querySelector('#f');
f.addEventListener('submit',function(ev) {
ev.preventDefault();
trapInput();
});
};
document.addEventListener('DOMContentLoaded',init);
})(window,document);
#t3 {
font-family: "Courier New";
font-size: xx-large;
}
#t3 td {
border: 1px solid silver;
width: 1em;
height: 1em;
vertical-align: middle;
text-align: center;
}
#f {
position: relative;
}
#f label, input, button {
float: left;
width: 200px;
}
#f label, button {
clear: left;
}
hr {
clear: both;
visibility: hidden;
}
<form id="f">
<label for="currentuser">Current User</label>
<input type="text" readonly id="currentuser" name="currentuser" />
<label for="square">What Square (1-9)?</label>
<input type="number" step="1" min="1" max="9" id="square" name="square" />
<label for="status">Game Status</label>
<input type="text" readonly id="status" name="status" value="Virgin Game" />
<button type="button" id="go">make move</button>
</form>
<hr />
<table id="t3">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<pre id="debug"></pre>

Related

tic tac toe how to keep the game on until win or tie

I am writing a tic tac toe game using JavaScript(no DOM) in console.
I started by doing only one player game and only with 'X'. When the player chooses the row index and the column index and then it store inside an array(Move), but I'm stuck, the player able to do only one move, and that's it. I really dont know what to do from there.
// Variables
let playerName, playerMove = [],
playerShape, boardGame;
// Functions
// Get And Check Name
function getCheckName() {
let name = prompt("Please Enter Your Name");
while (name == null || !isNaN(name) || name == ' ') {
alert("Numbers And Spaces Not Allowed");
name = prompt("Please Enter Your Name");
}
alert("Welcome " + name);
return name;
}
playerName = getCheckName();
playerShape = 'X';
//----------------------------------------------------------------------------------------
// // Get Row And Col
function getRowAndCol() {
let row, col, rowAndColArr = [];
row = parseInt(prompt("Please Enter A Row"));
while (row > 2 || row < 0 || row === null || isNaN(row)) {
alert("Not a Valid Row number");
row = parseInt(prompt("Please Enter A Row"));
}
rowAndColArr[rowAndColArr.length] = row;
col = parseInt(prompt("Please Enter A Col"));
while (col > 2 || col < 0 || col === null || isNaN(col)) {
alert("Not a Valid Col number");
col = parseInt(prompt("Please Enter A Col"));
}
rowAndColArr[rowAndColArr.length] = col;
return rowAndColArr;
}
playerMove = getRowAndCol();
//----------------------------------------------------------------------------------------
// Board Game
boardGame = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"]
];
function boardFn(board, move) {
for (let rw = 0; rw < board.length; rw++) {
for (let cl = 0; cl < board[rw].length; cl++) {
while (rw === move[0] && cl === move[1] && board[rw][cl] === "_") {
board[rw][cl] = playerShape;
}
}
}
return board;
}
let keepGame = boardFn(boardGame, playerMove);
do {
} while (condition);
console.log(checkWinner());
//----------------------------------------------------------------------------------------
// Check Win
function equal3(a, b, c) {
return (a == b && b == c && a != "_");
};
function checkWinner() {
let winner = null;
// Win In Horizontal
for (let rw = 0; rw < 3; rw++) {
if (equal3(boardGame[rw][0], boardGame[rw][1], boardGame[rw][2])) {
winner = boardGame[rw][0];
alert(playerName + " You Won line");
}
}
// Win In Vertical
for (let cl = 0; cl < 3; cl++) {
if (equal3(boardGame[0][cl], boardGame[1][cl], boardGame[2][cl])) {
winner = boardGame[cl][0];
alert(playerName + " You Won col");
}
}
// Win In Diagonal
if (equal3(boardGame[0][0], boardGame[1][1], boardGame[2][2])) {
winner = boardGame[0][0];
alert(playerName + " You Won diagonal");
}
// Win In Diagonal (Other Way)
if (equal3(boardGame[2][0], boardGame[1][1], boardGame[0][2])) {
winner = boardGame[2][0];
alert(playerName + " You Won digonal other");
}
return winner;
}
Updated code for two players
var board = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"]
];
//This function will prompt and get user name
function getName(player) {
let name = prompt("Please Enter " + player + " Name");
while (name == null || !isNaN(name) || name == ' ') {
alert("Numbers And Spaces Not Allowed");
name = prompt("Please Enter " + player + " Name");
}
alert("Welcome, " + name + "!");
return name;
}
//This function will prompt and get row and column from player
function getRowAndCol(player) {
let row, col, rowAndColArr = [];
row = parseInt(prompt(player + "! Please Enter A Row"));
while (row > 2 || row < 0 || row === null || isNaN(row)) {
alert("Not a Valid Row number");
row = parseInt(prompt(player + "! Please Enter A Row"));
}
rowAndColArr[rowAndColArr.length] = row;
col = parseInt(prompt(player + "! Please Enter A Col"));
while (col > 2 || col < 0 || col === null || isNaN(col)) {
alert("Not a Valid Col number");
col = parseInt(prompt(player + "! Please Enter A Col"));
}
rowAndColArr[rowAndColArr.length] = col;
//This block will check if the given box already marked. If so it will prompt for the move.
if (board[rowAndColArr[0]][rowAndColArr[1]] !== "_") {
alert("Already marked on the given box. Please Enter different row and column.!");
return getRowAndCol(player)
}
return rowAndColArr;
}
//This function will update the position with the given shape according to the move
function boardFn(board, move, shape) {
for (let rw = 0; rw < board.length; rw++) {
for (let cl = 0; cl < board[rw].length; cl++) {
while (rw === move[0] && cl === move[1] && board[rw][cl] === "_") {
board[rw][cl] = shape;
}
}
}
}
//This function will check if it is tie
function isTie() {
for (let rw = 0; rw < board.length; rw++) {
for (let cl = 0; cl < board[rw].length; cl++) {
if( board[rw][cl] === "_" ) {
return false;
}
}
}
return true;
}
//These functions will check whether the current player win or not
function equal3(a, b, c) {
return (a == b && b == c && a != "_");
};
function checkWinner(player) {
let winner = null;
// Win In Horizontal
for (let rw = 0; rw < 3; rw++) {
if (equal3(board[rw][0], board[rw][1], board[rw][2])) {
winner = board[rw][0];
alert(player + " You Won line");
}
}
// Win In Vertical
for (let cl = 0; cl < 3; cl++) {
if (equal3(board[0][cl], board[1][cl], board[2][cl])) {
winner = board[cl][0];
alert(player + " You Won col");
}
}
// Win In Diagonal
if (equal3(board[0][0], board[1][1], board[2][2])) {
winner = board[0][0];
alert(player + " You Won diagonal");
}
// Win In Diagonal (Other Way)
if (equal3(board[2][0], board[1][1], board[0][2])) {
winner = board[2][0];
alert(player + " You Won digonal other");
}
return winner;
}
var player1 = getName("Player 1") // getting player 1 name
alert(player1 + "! Your shape is 'X'");
var player2 = getName("Player 2") // getting player 2 name
alert(player2 + "! Your shape is 'O'");
// Variables to maintain current players and shape
var currentPlayer = ""
var currentShape = ""
// This block will get and validate moves until we get a winner
while (true) {
// This block will switch player after a move
if (currentPlayer == "") {
currentPlayer = player1;
currentShape = "X";
} else if (currentPlayer == player1) {
currentPlayer = player2;
currentShape = "O";
} else {
currentPlayer = player1;
currentShape = "X";
}
var move = getRowAndCol(currentPlayer);
boardFn(board, move, currentShape);
var status = "";
for (var i in board) {
for (var j in board[i]) {
status += board[i][j] + " ";
}
status += "\n";
}
console.log(status);
console.log("-------------------------------");
if (checkWinner(currentPlayer)) {
break;
} else if (isTie()) {
alert("Game tied.!")
break;
}
}

Javascript Minimax Function Exceedingly Slow

After initiating the tic-tac-toe AI move (it's currently written only to assess if miniMax can successfully run), it takes about 1 - 1.5 minutes to complete in firefox or chrome. Other tic-tac-toe game's minimax functions run on my computer in a fraction of the time.
Logging output has not led closer to the solution. Have verified that all terminal states return a score. Is there an obvious error here?
Codepen
$(document).ready(function() {
var state = {
status: "inProgress",
turn: "human", //can be human or AI
game: 1,
turnSwitch: function() {
if (this.turn == "human") {
return (this.turn = "AI");
} else if (this.turn == "AI") {
return (this.turn = "human");
}
}
};
//AI will use minimx algorithm to determine best possible move
function player(name, symbol) {
this.name = name;
this.symbol = symbol;
}
var human = new player("human", "X");
var AI = new player("AI", "O");
var board = {
board: [],
createBoard: function() {
for (let i = 0; i < 9; i++) {
this.board.push(i);
}
return this.board;
},
resetBoard: function() {
this.board = [];
createBoard();
},
//checks board for terminal state
terminalTest: function() {
for (let i = 0; i < 7; i += 3) {
if (
this.board[i] == this.board[i + 1] &&
this.board[i] == this.board[i + 2]
) {
if (typeof this.board[i] !== "number") {
return this.board[i];
}
}
}
for (let j = 0; j < 3; j++) {
if (
this.board[j] == this.board[j + 3] &&
this.board[j] == this.board[j + 6]
) {
if (typeof this.board[j] !== "number") {
return this.board[j];
}
}
}
if (
(this.board[0] == this.board[4] && this.board[0] == this.board[8]) ||
(this.board[2] == this.board[4] && this.board[2] == this.board[6])
) {
if (typeof this.board[4] !== "number") {
return this.board[4];
}
}
},
//checks for possible moves
findEmptyIndicies: function() {
return this.board.filter(a => typeof a == "number");
}
};
function miniMax(boardCurrent, player) {
//store all possible moves
var availableMoves = boardCurrent.findEmptyIndicies();
console.log("available moves length " + availableMoves.length);
//if terminal state, return score
var terminalCheck = boardCurrent.terminalTest();
if (terminalCheck === "X") {
//console.log(boardCurrent.board + " X wins score: -10")
return human.symbol == "X" ? { score: -10 } : { score: 10 };
} else if (terminalCheck === "O") {
//console.log(boardCurrent.board + " ) wins score: 10")
return human.symbol == "X" ? { score: 10 } : { score: -10 };
} else if (availableMoves.length === 0) {
console.log("availmoves length 0 " + availableMoves.length);
//console.log(boardCurrent.board + " score: 0")
return { score: 0 };
}
//array to store objects containing index and score through each iteration of available moves
var movesArray = [];
for (var i = 0; i < availableMoves.length; i++) {
//create object to store return score from each index branch
var move = {};
move.index = boardCurrent.board[availableMoves[i]];
boardCurrent.board[availableMoves[i]] = player.symbol;
//returned score from leaf node if conditionials at top of function are met
if (player.name == "AI") {
var miniMaxReturn = miniMax(boardCurrent, human);
move.score = miniMaxReturn.score;
console.log("move score " + move.score);
} else {
var miniMaxReturn = miniMax(boardCurrent, AI);
move.score = miniMaxReturn.score;
console.log("move score " + move.score);
}
boardCurrent.board[availableMoves[i]] = move.index;
movesArray.push(move);
}
var bestMove;
console.log("moves array length " + movesArray.length);
if (player.name === "AI") {
let bestScore = -1000;
for (let i = 0; i < movesArray.length; i++) {
if (movesArray[i].score > bestScore) {
bestScore = movesArray[i].score;
bestMove = i;
}
}
} else if (player.name === "human") {
let bestScore = 1000;
for (let i = 0; i < movesArray.length; i++) {
if (movesArray[i].score < bestScore) {
bestScore = movesArray[i].score;
bestMove = i;
}
}
}
return movesArray[bestMove];
}
/**function AIMove() {
console.log("ai move initiated");
var AIPosition = miniMax(board, AI);
//var index = AIposition.index;
//console.log(AIposition);
//$("#" + index).html(AI.symbol);
}**/
$(".cell").click(displayMove);
function displayMove() {
if (state.turn == "human") $(this).html(human.symbol);
board.board[this.id] = human.symbol;
state.turn = "AI";
miniMax(board, AI);
//AIMove();
console.log("AI move complete");
}
$(".cell").click(displayMove);
//on window load create board
board.createBoard();
});

JQuery / JavaScript Keyboard event

I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);

Finding out how many times an array element appears

I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>
Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.
With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3
Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..
When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;
Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}
Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5

JavaScript query string not working

I have this form
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input type="text" name="name1" id="name_1" tabindex="1" size="40" value="Test1" />
<br />
<br />
<input type="submit" id='view_1' value="Submit" tabindex="2" />
</fieldset>
<br />
<br />
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_2">Name:</label>
<input type="text" name="name2" id="name_2" tabindex="1" size="40" value="Test2" />
<br />
<br />
<input type="submit" id='view_2' value="Submit" tabindex="2" />
</fieldset>
</form>
When it submits to the next page I want to be able to get the query string for the button that was clicked and not see both strings when the page loads. The script that I am using on the receiving page is:
<script type="text/javascript">
document.write("Name: " + Request.QueryString("name1"));
document.write("Name: " + Request.QueryString("name2"));
</script>
and
/*TITLE: Client-Side Request Object for javascript by Andrew Urquhart (UK)
HOME: http://andrewu.co.uk/tools/request/
COPYRIGHT: You are free to use this script for any use you wish, the only
thing I ask you do is keep this copyright message intact with the script.
Please don't pass it off as your own work, but feel free to enhance it and send
me the updated version. Please don't redistribute - it makes it harder to distribute
new versions of the script. This script is provided as is, with no warranty of any
kind. Use it at your own risk.
VERSION: #1.41 2007-06-28 18:10 UTC*/
function RObj(ea) {
var LS = "";
var QS = new Object();
var un = "undefined";
var x = null; // On platforms that understand the 'undefined' keyword replace 'null' with 'undefined' for maximum ASP-like behaviour.
var f = "function";
var n = "number";
var r = "string";
var e1 = "ERROR: Index out of range in\r\nRequest.QueryString";
var e2 = "ERROR: Wrong number of arguments or invalid property assignment\r\nRequest.QueryString";
var e3 = "ERROR: Object doesn't support this property or method\r\nRequest.QueryString.Key";
var dU = window.decodeURIComponent ? 1 : 0;
function Err(arg) {
if (ea) {
alert("Request Object:\r\n" + arg);
}
}
function URID(t) {
var d = "";
if (t) {
for (var i = 0; i < t.length; ++i) {
var c = t.charAt(i);
d += (c == "+" ? " " : c);
}
}
return (dU ? decodeURIComponent(d) : unescape(d));
}
function OL(o) {
var l = 0;
for (var i in o) {
if (typeof o[i] != f) {
l++;
}
}
return l;
}
function AK(key) {
var auk = true;
for (var u in QS) {
if (typeof QS[u] != f && u.toString().toLowerCase() == key.toLowerCase()) {
auk = false;
return u;
}
}
if (auk) {
QS[key] = new Object();
QS[key].toString = function() {
return TS(QS[key]);
}
QS[key].Count = function() {
return OL(QS[key]);
}
QS[key].Count.toString = function() {
return OL(QS[key]).toString();
}
QS[key].Item = function(e) {
if (typeof e == un) {
return QS[key];
}
else {
if (typeof e == n) {
var a = QS[key][Math.ceil(e)];
if (typeof a == un) {
Err(e1 + "(\"" + key + "\").Item(" + e + ")");
}
return a;
}
else {
Err("ERROR: Expecting numeric input in\r\nRequest.QueryString(\"" + key + "\").Item(\"" + e + "\")");
}
}
}
QS[key].Item.toString = function(e) {
if (typeof e == un) {
return QS[key].toString();
}
else {
var a = QS[key][e];
if (typeof a == un) {
Err(e1 + "(\"" + key + "\").Item(" + e + ")");
}
return a.toString();
}
}
QS[key].Key = function(e) {
var t = typeof e;
if (t == r) {
var a = QS[key][e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e3 + "(" + (e ? e : "") + ")");
}
}
QS[key].Key.toString = function() {
return x;
}
}
return key;
}
function AVTK(key, val) {
if (key != "") {
var key = AK(key);
var l = OL(QS[key]);
QS[key][l + 1] = val;
}
}
function TS(o) {
var s = "";
for (var i in o) {
var ty = typeof o[i];
if (ty == "object") {
s += TS(o[i]);
}
else if (ty != f) {
s += o[i] + ", ";
}
}
var l = s.length;
if (l > 1) {
return (s.substring(0, l-2));
}
return (s == "" ? x : s);
}
function KM(k, o) {
var k = k.toLowerCase();
for (var u in o) {
if (typeof o[u] != f && u.toString().toLowerCase() == k) {
return u;
}
}
}
if (window.location && window.location.search) {
LS = window.location.search;
var l = LS.length;
if (l > 0) {
LS = LS.substring(1,l);
var preAmpAt = 0;
var ampAt = -1;
var eqAt = -1;
var k = 0;
var skip = false;
for (var i = 0; i < l; ++i) {
var c = LS.charAt(i);
if (LS.charAt(preAmpAt) == "=" || (preAmpAt == 0 && i == 0 && c == "=")) {
skip=true;
}
if (c == "=" && eqAt == -1 && !skip) {
eqAt=i;
}
if (c == "&" && ampAt == -1) {
if (eqAt!=-1) {
ampAt=i;
}
if (skip) {
preAmpAt = i + 1;
}
skip = false;
}
if (ampAt>eqAt) {
AVTK(URID(LS.substring(preAmpAt, eqAt)), URID(LS.substring(eqAt + 1, ampAt)));
preAmpAt = ampAt + 1;
eqAt = ampAt = -1;
++k;
}
}
if (LS.charAt(preAmpAt) != "=" && (preAmpAt != 0 || i != 0 || c != "=")) {
if (preAmpAt != l) {
if (eqAt != -1) {
AVTK(URID(LS.substring(preAmpAt,eqAt)), URID(LS.substring(eqAt + 1,l)));
}
else if (preAmpAt != l - 1) {
AVTK(URID(LS.substring(preAmpAt, l)), "");
}
}
if (l == 1) {
AVTK(LS.substring(0,1),"");
}
}
}
}
var TC = OL(QS);
if (!TC) {
TC=0;
}
QS.toString = function() {
return LS.toString();
}
QS.Count = function() {
return (TC ? TC : 0);
}
QS.Count.toString = function() {
return (TC ? TC.toString() : "0");
}
QS.Item = function(e) {
if (typeof e == un) {
return LS;
}
else {
if (typeof e == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return QS[i];
}
}
Err(e1 + "().Item(" + e + ")");
}
else {
return QS[KM(e, QS)];
}
}
return x;
}
QS.Item.toString = function() {
return LS.toString();
}
QS.Key = function(e) {
var t = typeof e;
if (t == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return i;
}
}
}
else if (t == r) {
var e = KM(e, QS);
var a = QS[e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e2 + "().Key(" + (e ? e : "") + ")");
}
Err(e1 + "().Item(" + e + ")");
}
QS.Key.toString = function() {
Err(e2 + "().Key");
}
this.QueryString = function(k) {
if (typeof k == un) {
return QS;
}
else {
if (typeof k == n) {
return QS.Item(k);
}
var k = KM(k, QS);
if (typeof QS[k] == un) {
t = new Object();
t.Count = function() {
return 0;
}
t.Count.toString = function() {
return "0";
}
t.toString = function() {
return x;
}
t.Item = function(e) {
return x;
}
t.Item.toString = function() {
return x;
}
t.Key = function(e) {
Err(e3 + "(" + (e ? e : "") + ")");
}
t.Key.toString = function() {
return x;
}
return t;
}
else {
return QS[k];
}
}
}
this.QueryString.toString = function() {
return LS.toString();
}
this.QueryString.Count = function() {
return (TC ? TC : 0);
}
this.QueryString.Count.toString = function() {
return (TC ? TC.toString() : "0");
}
this.QueryString.Item = function(e) {
if (typeof e == un) {
return LS.toString();
}
else {
if (typeof e == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] != f && ++c == e) {
return QS[i];
}
}
Err(e1 + ".Item(" + e + ")");
}
else {
return QS[KM(e, QS)];
}
}
if (typeof e == n) {
Err(e1 + ".Item(" + e + ")");
}
return x;
}
this.QueryString.Item.toString = function() {
return LS.toString();
}
this.QueryString.Key = function(e) {
var t = typeof e;
if (t == n) {
var e = Math.ceil(e);
var c = 0;
for (var i in QS) {
if (typeof QS[i] == "object" && (++c == e)) {
return i;
}
}
}
else if (t == r) {
var e = KM(e, QS);
var a = QS[e];
return (typeof a != un && a && a.toString() ? e : "");
}
else {
Err(e2 + ".Key(" + (e ? e : "") + ")");
}
Err(e1 + ".Item(" + e + ")");
}
this.QueryString.Key.toString = function() {
Err(e2 + ".Key");
}
this.Version = 1.4;
this.Author = "Andrew Urquhart (http://andrewu.co.uk)";
}
var Request = new RObj(false);
How can i only display the string for the button that was clicked and not see both strings?
For identifying the button that's clicked, you need to have two forms. name1 and view_1 should be enclosed in one form and the other form should have name2 and view_2. This is the only way to identify the clicked button. If name1 is present then view_1 is clicked, if name2 is present then view_2 is clicked.
UPDATE: Added code sample
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input type="text" name="name1" id="name_1" tabindex="1" size="40" value="Test1" />
<br />
<br />
<input type="submit" id='view_1' value="Submit" tabindex="2" />
</fieldset>
</form>
<br />
<br />
<form name="exampleform1" id="exampleform1" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_2">Name:</label>
<input type="text" name="name2" id="name_2" tabindex="1" size="40" value="Test2" />
<br />
<br />
<input type="submit" id='view_2' value="Submit" tabindex="2" />
</fieldset>
</form>
You are placing both name fields in one form. If you want just the one value, use two forms.
I rewrote your example page
Now you have 2 forms exampleform and exampleform2. Both submit data to the same page example123.html
Note also in the second form I renamed everything from name_2 to name_1 keeping it consistant with the first form
<form name="exampleform" id="exampleform" action="example123.html" method="get">
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input name="name1" id="name_1" tabindex="1" size="40" value="Test1" type="text">
<br>
<br>
<input value="Submit" tabindex="2" type="submit">
<input value="Reset" tabindex="2" type="reset">
</fieldset>
</form>
<form name="exampleform2" id="exampleform2" action="example123.html" method="get">
<br>
<br>
<fieldset>
<legend>Creating The Querystring</legend>
<label for="name_1">Name:</label>
<input name="name1" id="name_1" tabindex="1" size="40" value="Test2" type="text">
<br>
<br>
<input value="Submit" tabindex="2" type="submit">
<input value="Reset" tabindex="2" type="reset">
</fieldset>
</form>
Now in your response page all you need to look for is
document.write("Name: " + Request.QueryString("name1"));
name2 no longer exists
[UPDATE]
As per a comment you made below. You can not have more then one submit button per form where they submit different data unless you validate the data onsubmit.
There is a serious security problem with what you are trying to do, as I will explain below. But you can still utilize your technique if you follow through.
Using your current code, you could do it by making sure the second file is named "example123.html", is saved in the same directory as the other file, and that your document.write() calls occur after the Request object is defined. Also check for null values, which are made particularly difficult by this class which returns an object rather than a string, so it can not be as easily compared with null.
var name1 = Request.QueryString("name1"),
name2 = Request.QueryString("name2");
if (name1+'' != 'null') {
document.write("Name: " + name1);
}
if (name2+'' != 'null') {
document.write("Name: " + name2);
}
That being said the code you are using follows a number of (other) bad practices, and while convenient perhaps for some people in mimicking the ASP Request behavior is really better abandoned in favor of other more standard practices.
We made a similar function for those coming instead from a PHP background (see http://phpjs.org/functions/import_request_variables:431 ) which if you use the following code, will let you access your variables like this:
ini_set('phpjs.getVarsObj', $_GET = {});
import_request_variables('g');
if ($_GET['name1']) {
document.write(htmlspecialchars($_GET['name1']));
}
if ($_GET['name2']) {
document.write(htmlspecialchars($_GET['name2']));
}
HOWEVER!!.... Please note the important warning though that if you use functions like the one you found (or ours), you are checking the URL for this information, since 1) your form is method=get, and 2) since client-side JavaScript can't by itself detect any other methods of how the data was sent to it, and thus if you are not careful about what you do with the $_GET variable's contents, someone could link someone to your site in such a way as to allow your site's visitor's cookie-stored passwords to be stolen or do other mischief. In other words, as with server-side code, be aware of XSS (Cross-site scripting).
For example, if someone filled in the name on your form with this code:
<script>alert('boo!');</script>
...in some browsers, besides for the person submitting the form, anyone who clicks on the link that results (e.g., if a hacker tempted someone to click it), will see that alert. This may not seem so serious, but if the JavaScript instead detects their cookie password on your site, they could craft it so that the script sends their cookies to their own site.
A somewhat safer solution is to use a function such as http://phpjs.org/functions/htmlspecialchars:426 to escape the potentially unsafe characters like < and & .
document.write(htmlspecialchars($_GET['name1']);
This function was based on the function of the same name in PHP, so it can be used there for the same purppose.
(If you actually WANT to allow HTML to be included in the page, that is more challenging and happens to be a question I just asked: JavaScript-based X/HTML & CSS sanitization )

Categories