JavaScript display new page when submit HTML form - javascript

Suppose I have 2 html files: form.html and confirm.html
form.html just have a text field and a submit button, when you hit submit it will display what you just typed in text field.
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script type="text/javascript">
function display(){
document.write("You entered: " + document.myform.data.value);
}
</script>
</HEAD>
<BODY>
<center>
<form name="myform">
<input type="text" name="data">
<input type="submit" value="Submit" onClick="display()">
</form>
</BODY>
</HTML>
Now I want that when hit submit button it will display entered value in confirm.html. What should I do? I mean what should be in confirm.html and how data from form.html be used in other location, do I need create a separate JavaScript file to store JS function so I can use it in both 2 html files. I am kind of new to all kind of stuff.
Note: No PHP or server side language or anything super here, just 2 html files in my Desktop and I want to test using FireFox.
Thank you!

You can try using localStorage or cookies. Check one of the 2 solutions found below...
1 - If you have HTML5, you can store the content of you input into the localStorage.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
2 - Also, as #apprentice mentioned, you can also use cookies with HTML standards.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Function for storing to cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into a cookie
setCookie("mytext", mytext, 300);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Function for retrieveing value from a cookie
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into a cookie
var mytext = getCookie("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>

What you could do is submit the form using a get method (method="get"), and send it to your confirm.html page (action="./confirm.html").
Then, you could use jQuery to retrieve the values from the URL from your confirm.html page.
This website provides a method to do that: http://jquerybyexample.blogspot.com/2012/06/get-url-parameters-using-jquery.html .
Then, all you have to do is call your display() method.

Seams like a fit for persist.js, which will let you save and load data in the user's browser. After including its javascript file, you can save data like this:
var store = new Persist.Store('My Application');
store.set('some_key', 'this is a bunch of persistent data');
And you can later retrieve the saved data in another html page like the following:
var store = new Persist.Store('My Application');
val = store.get('some_key');

You could also, instead of changing the page, change the content of the page. Upon submission just change the page using the innerHtml variable.

Related

use value from input field in html dialog box to var in code.gs using Google Apps Script

I have a dialog box where user can select a year. Then I want the server to process the selected value in the function doSomethingWithCompetitionYear(theYear).
Looked at several discussions, but can't get it working. Looks like I need to do something with .withSuccesHandler().
Code.gs
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createTemplateFromFile('DropDown_NewCompetitionFile');
thisYear = new Date();
htmlDlg.thisYear = thisYear.getFullYear();
htmlDlg.nextYear = htmlDlg.thisYear + 1;
htmlDlg = htmlDlg.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Make selection');
};
function doSomethingWithCompetitionYear(theYear) {
var ui = SpreadsheetApp.getUi();
ui.alert(theYear);
}
HTML doc
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Year
<select name="Competition_year" id="Competition_year" type="integer">
<option value=<?= thisYear?>><?= thisYear?></option>
<option value="nextYear"><?= nextYear?></option>
</select>
<hr/>
<button onmouseup="closeDia()">Submit</button>
<script>
var theYear = document.getElementById("Competition_year").value;
google.script.run.doSomethingWithCompetitionYear();
window.closeDia = function() {
google.script.host.close();
};
</script>
</body>
</html>
Here's a simple boiler plate for doing something with .withSuccessHandler
I added some JQuery, a msgdiv, withSuccessHandler() and a doSomethingWithCompetitionYear() server function.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
Year
<select name="Competition_year" id="Competition_year" type="integer">
<option value=<?= thisYear?>><?= thisYear?></option>
<option value="nextYear"><?= nextYear?></option>
</select>
<hr/>
<button onmouseup="closeDia()">Submit</button>
<div id="msgdiv"></div>
<script>
var theYear = document.getElementById("Competition_year").value;
google.script.run
.withSuccessHandler(function(msg){
document.getElementById("msgdiv").innerHTML=msg;
}))
.doSomethingWithCompetitionYear();
window.closeDia = function() {
google.script.host.close({year:$("#competition_year").val()});
};
</script>
</body>
</html>
code.gs:
function doSomethingWithCompetitionYear(obj) {
return Utilities.formatString('I did something with this year: %s',obj.year);
}
Situation:
If I understand you correctly you have a dialog box with two options, and you want to pass information on the selected option (in this case, 2020 or 2021) to the server-side function doSomethingWithCompetitionYear(); when the Submit button is clicked.
Issues:
If that's the case, you don't actually need a success handler. You just need to pass the selected value as a parameter of doSomethingWithCompetitionYear(theYear);.
Also, if you want this to happen when the Submit button is clicked. You should add this to the closeDia function. Otherwise, doSomethingWithCompetitionYear(); will run before submission.
Finally, if you want to pass the next year (2021), and not the string "nextYear", you'll have to use scriplets on the element's value.
Modification 1. Next year value:
Replace this:
<option value="nextYear"><?= nextYear?></option>
For this:
<option value=<?= nextYear?>><?= nextYear?></option>
Modification 2. Calling server-side function when button is clicked:
Replace this:
<script>
var theYear = document.getElementById("Competition_year").value;
google.script.run.doSomethingWithCompetitionYear();
window.closeDia = function() {
google.script.host.close();
};
</script>
For this:
<script>
window.closeDia = function() {
var theYear = document.getElementById("Competition_year").value;
google.script.run.doSomethingWithCompetitionYear(theYear); // theYear parameter has to be passed to server-side function
google.script.host.close();
};
</script>
Note:
If you want to use information coming from doSomethingWithCompetitionYear(theYear); in the client-side, you should use a success handler, which can call a client-side function that will get this data as a parameter (the server-side function, called by google.script.run doesn't return anything by itself, it needs a callback function). It would be something like this:
google.script.run.withSuccessHandler(yourClientSideFunction).doSomethingWithCompetitionYear(theYear);
Reference:
Class google.script.run (Client-side API)

How to make a JavaScript result appear on the same page, not in an alert popup window

I was wondering instead of using the alert function to show the function result if there was a way to print it in a text field on the same page as the original variable input. Thanks!
create a div in your body for result like
<div id="result"></div>
update from script like
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = <your value>
Without additional libraries, using only browser functions, you can do this with the document.getElementById() function like this:
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" id="textfield">
</body>
<script>
function someFunction() {
return "Hello world!";
}
document.getElementById('textfield').value = someFunction();
</script>
<html>

How to pass parameters to javascript function that are defined outside the form tag?

i am trying to pass a parameter to a javascript function thats been defined outside the tag.but when i try to use it in the javascript function it shows undefined.i am using alert to print the value both in the jsp page and in javascipt function...please help
<html>
<script type="text/javascript">
js_valueDate = '<%=valueDate%>';
alert(js_valueDate) **//displays correct value here**
</script>
<body>
<form>
....some html...
<td width=27%><input type=text name="ValDate"
onchange = "javascript:validateDate(document.f1.ValDate,js_valueDate);"></td>
......some html....
</form>
</body>
</html>
and this is my javascript function:
function validateDate(ValDate,origValDate) {
var valueDate=ValDate.value;
var OrigvalueDate=origValDate.value;
confirm(valueDate);
confirm(OrigvalueDate); **//displays undefined here**
var hh=replaceAll(valueDate,'-','');
confirm(hh);
if (replaceAll(valueDate,"-","")<=valueDate<=replaceAll(OrigvalueDate,"-","")) {
return true;
} else {
alertPopup("Please enter a valid value date");
document.f1.ValDate.focus();
return false;
}
}
Since you are passing the value itself there is no need of the statement var OrigvalueDate=origValDate.value;
Here is a small example which i have written which explains both the situation
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Check </title>
<script>
function display(v)
{
var d=v.value;
alert(v);
alert(d);
}
jval="qwerty";
</script>
</head>
<body>
<input type="button" value="check" onclick="javascript:display(jval)"/>
</body>
</html>
Try something like this. This 'll help you
<html>
<script type="text/javascript">
js_valueDate = '<%=valueDate%>';
alert(js_valueDate) **//displays correct value here**
var ValidationHandler = {
validateDate:function(ValDate,origValDate){
var valueDate=ValDate.value;
var OrigvalueDate=origValDate.value;
confirm(valueDate);
confirm(OrigvalueDate); **//displays undefined here**
var hh=replaceAll(valueDate,'-','');
confirm(hh);
if (replaceAll(valueDate,"-","")<=valueDate<=replaceAll(OrigvalueDate,"-",""))
{
return true;
}
else
{
alertPopup("Please enter a valid value date");
document.f1.ValDate.focus();
return false;
}
}
};
</script>
<body>
<form>
....some html...
<td width=27%><input type=text name="ValDate"
onchange = "javascript:ValidationHandler.validateDate(document.f1.ValDate,js_valueDate);"></td>
......some html....
</form>
</body>
</html>

How to send xml string from action class to jsp in struts2

I am very much new to struts 2. I am creating a sample example. In my example i have a login.jsp. Currently i have not implemented any logic in my jsp page, i am just checking if the user has inputed value in username and password textBox. From the login.jsp, the control gets redirected to callWebservice.java action class. Here i am calling a webservice which is giving me result in form of xml. On success i am redirecting from this action class to showResult.jsp. Here i want to capture my result xml in a variable using javascript.
Here is my code on showResult.jsp :
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Show Result</title>
<script type="text/javascript">
function showResult() {
alert("Here it comes ");
var result = <s:property value="key1" />
alert("Before Display");
}
</script>
</head>
<body onload="showResult()">
<form action="#" method="POST" >
<div id="headerbg">
<h1 id="headerTag">Webs service Result</h1>
</div>
Result obtained by invoking webservice is : <s:property value="key1" />
</form>
</body>
</html>
I am getting the result xml from this property tag i.e <s:property value="key1" />.
I just want to know how can i store this result in a variable using
JAVASCRIPT.
Change the var result as
var result = "<s:property value='key1'/>";
i.e.
<script type="text/javascript">
function showResult() {
alert("Here it comes ");
var result = "<s:property value='key1'/>";
alert("Before Display");
}
</script>
replace
var result = <s:property value="key1" />
by
var result = "<s:property value=\"key1\" />"

Transfer data from one HTML file to another

I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript.
Here's what I've done so far to test it:
testing.html
<html>
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
asd.js
function testJS()
{
var b = document.getElementById('name').value
document.getElementById('here').innerHTML = b;
}
test.html -> ads.js(will extract value from the test.html and set to next.html) -> next.html
Try this code:
In testing.html
function testJS() {
var b = document.getElementById('name').value,
url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
And in next.html:
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc.
Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.
PS. i'm an non-native english speaker, will you please correct my message, if necessary
The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:
localStorage["key"] = value;
... in another page ...
value = localStorage["key"];
You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.
Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
Session Cookies
HTML5 LocalStorage
POST the variable in the url and retrieve them in next.html via window object
With the Javascript localStorage class, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key.
Example -
Pageone.html -
<script>
localStorage.setItem("firstname", "Smith");
</script>
Pagetwo.html -
<script>
var name=localStorage.getItem("firstname");
</script>
I use this to set Profile image on each page.
On first page set value as:
localStorage.setItem("imageurl", "ur image url");
or on second page get value as :
var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);
you can simply send the data using window.location.href first store the value to send from testing.html in the script tag, variable say
<script>
var data = value_to_send
window.loaction.href="next.htm?data="+data
</script>
this is sending through a get request
HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed
document.getElementById('here').innerHTML = data.name;
This needed to be changed to
document.getElementById('here').innerHTML = data.n;
I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .
<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>
<body>
<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
client side scripting
function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}
jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.
jquery load function http://api.jquery.com/load/
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>
I coded the answers from Alex Fitiskin, and added a bit of extra code.
I added a parameter to the onLoad function to get the form's submit event, and prevent it's default behaviour first.
Here's the code:
test.html
<html>
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get" onsubmit="return testJS(event)">
name:<input type="text" id="name" name="n">
<input type="submit" value="next">
<!-- <button type="button" id="print" onClick="testJS()"> Print </button> //Button not needed anymore -->
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
test.js
function testJS(e) {
e.preventDefault();
var b = document.getElementById('name').value,
url = 'http://path_to_next_location/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
function onLoad() {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {},
tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
window.onload = onLoad;
This way the onload function will be replaced with the custom onLoad function, and the form will not be submitted the default way, but instead using the code inside the testJS function.
Avoid localstorage use as data are not safe with get method. Best option is to use script set to module and then export & import data via 2 js files to html file. Variable value can be passed between pages using module method.

Categories