Coder123
Coder123

Reputation: 854

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.

What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).

HTML:

<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script> 
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>

</head>
<body>
 <form >
      player one name: <input type="text" id="firstname"><br>
      player two name: <input type="text" id="secondname"><br>
      <input type="submit" onclick="checkNames();"/>
</form>

</body>
</html>

JavaScript:

function checkNames(){
    var nameOne = document.getElementById("firstname").value;
    var nameTwo = document.getElementById("secondname").value;
    //window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
    //window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
    window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}

I have commented the two other options I tried which also do not work.

Upvotes: 0

Views: 227

Answers (3)

Adrian David Smith
Adrian David Smith

Reputation: 598

You are using an HTML form... this means that your submit button will fire and try to submit your form.

In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.

function checkNames() {
    event.preventDefault();
    var nameOne = document.getElementById("firstname").value;
    var nameTwo = document.getElementById("secondname").value;
    window.location.href = 'SOME-PATH/Game.html';
}

Upvotes: 1

Rodrigo5244
Rodrigo5244

Reputation: 5545

To redirect to a page in your computer you can use:

window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';

There are more than one way of passing the values to another page. Here is an example using query string.

In the page that has the values.

var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;

In the page receiving the values.

var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];

Upvotes: 1

anas p a
anas p a

Reputation: 411

Use window.location="url";

Upvotes: 0

Related Questions