How to dispaly values from a different html page using javascript? - javascript

I have the following code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
</body>
</html>
Another HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript">
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
</script>
</body>
</html>
I am trying to pass on the value 'name' and retrieve it on a different html page (results.html). How do I accomplish this? I am not sure what I am doing wrong. Please help. Thank you!

pass the variable in the url using GET like :
<form method="get" action="result.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
and retrieve it in the other page like :
<h2> Your Form Has Been Submitted </h2>
<script>
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
console.log(name) // this is your variable
document.querySelector('h2').innerText += name;
</script>

One way is: you could use the 'get' method on the form, and not 'post':
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OrderUp</title>
</head>
<body>
<!-- Use method 'GET', not 'POST', to pass the form values via the url in the address bar -->
<form method="GET" action="results.html">
Name :
<input name="name" type="text">
<br>
<input value="Submit" type="submit">
</form>
</body>
</html>
Then, in result.html, use javascript to extract the name value from the page url.
result.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<span>Name Submitted: </span>
<span id="name-label"></span>
<script type="text/javascript">
// Get the value passed in the url by the form
var querystring = location.search;
// => ?name=Roger
// Remove the '?' at the beginning
var nameValuePair = querystring.replace(/^\?/, '');
// => name=Roger
// Split into parts
var parts = nameValuePair.split('=');
// The name is the second value
var name = parts[1];
// Set the name in the HTML element.
document.getElementById('name-label').innerHTML = name;
</script>
</body>
</html>

You cannot simply take a function from one html and put it into another. Using pure JavaScript and HTML the best way to accomplish this would be to make a JavaScript file, put the function there and load it on both pages. That way if you edit the function in one place, it will change in both.
The code would look like this:
Page 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
Page 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
results.js
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}

Probably the simplest would be to append it to the url:
<script>
function goToResults() {
window.location = "results.html#" + document.getElementbyId('name').value;
}
document.getElementById("submit").onclick = goToResults;
</script>
<input id = "name" />
<button id = "submit" > Submit </ button>
And on results.html just get it from the location:
document.body.innerHTML += document.location.href.split("#")[1];

You need a way to save the information you want to share between pages. There are many options for javascript each with pros and cons
use the uri hash:
location.hash = myValue / var retrieveValue = location.hash;
use localstorage:
localStorage.setItem("key", "value"); / localStorage.getItem("key");
also document.cookie is an option, (you can look that one up as it's slightly more involved to implement with many good answes already around)

Related

How do I trigger a JavaScript function when a button is pressed in HTML code

I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>

How to access form element in javascript function?

I'm trying to access an element in javascript function so as to autocomplete the user search, using autocomplete API.
It is not working as the JS code is not able to access that element.
My javascript code:
<script>
$(function() {
$("#q").autocomplete({
source: "/api/get_drugs/",
minLength: 2,
});
});
</script>
My reference for search.
My Form:
<form id = "myForm" method="GET" action="{% url 'search' %}">
<input style="width:340px;height:37px;" size="30" type="text" id = 'q' name = 'q' placeholder="Search products or categories"/>
<input type="submit" value="Search" >
</form>
Here the input target field has id and name- 'q'.
The bellow code works perfect . Now make sure that the response you are getting from the api is an array .
Or else do one thing , store the response of API in some variable and assign that variable to key Source . For example :
source : apiResponseVariable //must be array .
$(function() {
$("#q").autocomplete({
source: ["hello" , "how"],
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>GnG</title>
</head>
<body>
<form id = "myForm" method="GET" action="{% url 'search' %}">
<input style="width:340px;height:37px;" size="30" type="text" id='q' name = 'q' placeholder="Search products or categories"/>
<input type="submit" value="Search" >
</form>
</body>
</html>
You can checkout my running run .

Implementing sessionStorage in between page hops

I have two codes, one is form.html:
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Form</title>
<script type="text/javascript">
$(function(){
$("#sub").on("click", function(){
sessionStorage.n1 = $("#no1").val();
sessionStorage.n2 = $("#no2").val();
location.href = "main.html";
});
});
</script>
</head>
<body>
No1:<input type="text" id="no1">
No2:<input type="text" id="no2">
<br>
<input type="button" value="Submit" id="sub">
</body>
</html>
and the other is main.html:
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Main</title>
<script type="text/javascript">
var n1_arr = new Array();
var n2_arr = new Array();
$(function(){
n1_arr.push(sessionStorage.getItem("n1"));
n2_arr.push(sessionStorage.getItem("n2"));
$("#a").click(function(){
location.href = "form.html";
});
$("#s").click(function(){
for(var i = 0; i < n1_arr.length; i++)
{
alert(n1_arr[i] + " and " + n2_arr[i]);
}
});
});
</script>
</head>
<body>
<input type="button" value="Add" id="a">
<input type="button" value="Show" id="s">
</body>
</html>
I want these to work like this:
First, main.html will open, and on clicking on the 'Add' button, the form.html will open in the same browser tab. The user will enter two numbers in the text boxes with id's no1 and no2. The user will then click on 'Submit' and then again, main.html should open(again in the same browser tab). The user will continue to do this for as long as he wants. On clicking the 'Show' button, alerts of all the values entered by the user, separately in pairs, will occur. How can I achieve this? In this case, only the last entered pair is alerted.
first you have to run the command on console:
sessionStorage.clear();
main.html
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Main</title>
<script type="text/javascript">
var n1_arr = JSON.parse(sessionStorage.getItem("n1")) || [];
var n2_arr = JSON.parse(sessionStorage.getItem("n2")) || [];
$(function(){
$("#a").click(function(){
location.href = "form.html";
});
$("#s").click(function(){
for(var i = 0; i < n1_arr.length; i++)
{
alert(n1_arr[i] + " and " + n2_arr[i]);
}
});
});
</script>
</head>
<body>
<input type="button" value="Add" id="a">
<input type="button" value="Show" id="s">
</body>
</html>
form.html
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Form</title>
<script type="text/javascript">
$(function(){
$("#sub").on("click", function(){
var n1 = sessionStorage.n1 || [];
if(n1.length > 0){
n1 = JSON.parse(sessionStorage.n1);
}
n1.push($("#no1").val());
sessionStorage.n1 = JSON.stringify(n1);
var n2 = sessionStorage.n2 || [];
if(n2.length > 0){
n2 = JSON.parse(sessionStorage.n2);
}
n2.push($("#no2").val());
sessionStorage.n2 = JSON.stringify(n2);
location.href = "main.html";
});
});
</script>
</head>
<body>
No1:<input type="text" id="no1">
No2:<input type="text" id="no2">
<br>
<input type="button" value="Submit" id="sub">
</body>
</html>
It would appear you are overwriting your existing n1 and n2 values.
sessionStorage stores key value pairs, with the value being a string. When you do sessionStorage.setItem('n1', 'test') it will overwrite the existing value.
What you need to do is read the existing value (it will be a string), parse it, append your new value on the end, then insert the whole object back into storage. When storing an object it will be best to stringify it as JSON first.
If you need to store complex objects like arrays etc you may find it better to use indexedDB.
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

Store textbox values in a div tag

I have a textbox having id=add, a div having id=get and a button named Add. Now I'm trying to enter values in textbox, save them in to an array and then save that array elements in the div tag (using javascript). But I'm unable to do so. Please help.
<html>
<head>
<title>Content</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="stylesheets/keyword.css" rel="stylesheet">
<SCRIPT language="javascript">
//
var data = new array();
data= document.getElementById('add').value;
function copy()
{
document.getElementById('get').innerHTML=data;
// document.getElementById('get').innerHTML= document.getElementById('add').value;
// return true;
}
</SCRIPT>
</head>
<body>
<input type="text" name="add" id="add"/>
<input type="button" name="but1" onclick="copy()" value="Add"/>
<div id="get" class="keyword"></div>
</body>
</html>
Update your code as,
<html>
<head>
<title>Content</title>
<script language="javascript">
function copy() {
var data = document.getElementById('add').value;
document.getElementById('get').innerHTML += data + "<br/>";
}
</script>
</head>
<body>
<input type="text" name="add" id="add" />
<input type="button" name="but1" onclick="copy()" value="Add" />
<div id="get" class="keyword">
</div>
</body>
</html>
PS:Array (not array) is not required here,
This is because data doesn't have any value, you are trying to read the value of the text box before setting a value and also it should be Array()
Try this instead
function copy()
{
var data = new Array();
data= document.getElementById('add').value;
document.getElementById('get').innerHTML=data;
}
JsBin
Three issues in your code:
array() is not recognized in javascript, it's Array().
You are trying to read the value of the text box before a value can be set to it here:
data= document.getElementById('add').value;
function copy(){
It should be:
function copy()
{
data[0]= document.getElementById('add').value;
data is an array. If you want to store a value, it should be used with an index.
JSFiddle
<html>
<head>
<title>Content</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="stylesheets/keyword.css" rel="stylesheet">
<SCRIPT language="javascript">
//
var data = new Array();
function copy()
{
data = document.getElementById('add').value;
document.getElementById('get').innerHTML = data; document.getElementById('get').innerHTML= document.getElementById('add').value;
// return true;
}
</SCRIPT>
</head>
<body>
<input type="text" id="add"/>
<input type="button" name="but1" onclick="copy()" value="Add"/>
<div id="get" class="keyword"></div>
</body>
</html>

passing variable to javascript function and using it in document.form?

<!DOCTYPE html>
<html>
<head>
<title>Database test</title>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
function validateForm(n)
{
var x=document.forms.SignUp.n.value;
alert("*"+x+"*");
}
</script>
</head>
<body>
<h1>Just a Database test</h1>
<form name="SignUp" action="http://127.0.0.1/cgi-bin/connectivity.cgi" onsubmit="return validateForm();" method="post">
Ename :<input type="text" name="ename" onchange="validateForm('ename');"><br><p id="error_1"></p>
<input type="submit" value="Send">
</form>
</body>
</html>
I am trying to pass the user input value by onchange="validateForm('ename') but it does not seem to work i dont get anything.
instead if i change function to this then it works but again i need to pass it as varaible from onchange="validateForm('ename').
function validateForm(n)
{
alert("*"+n+"*");
}
You should pass the element itself, which is this inside an inline handler:
validateForm(this);
function validateForm(elem)
alert(elem.value);
}
One way to make it work, without changing your function call:
function validateForm(n) {
var x = document.forms.SignUp[n].value;
alert("*"+x+"*");
}

Categories