I have successfully taken input data from a form and output it as console.log('input') in setting.html. But how do I send this variable to another file called index.html? Here is setting.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>settings></title>
</head>
<body>
<form action=index.html>
<input id="userinput" type="text">
<button onclick="myfunction()">Click me</button>
</form>
</body>
<script>
var theinput='';
function myfunction() {
theinput=document.getElementById("userinput").value;
console.log(theinput);
}
</script>
</html>
and index.html is
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="settings.html"></script>
</head>
<body>
<a href="setting.html">settings</a>
<button onclick="theFunction()">generate pdf</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script>
input=document
function theFunction() {
var num = 'this is....';
console.log(num);
const pdf = new jsPDF();
pdf.text(num,10,10);
pdf.save('a4.pdf');
}
</script>
</html>
Thanks,
CodePudding user response:
in settings capture your submit button's click and set a localStorage item value to the user input. Then redirect the user to the index.html file
<form>
<input id="userinput" name="input" type="text">
<button type="button" >Submit</button>
</form>
<script>
let btn = document.querySelector(".btn-submit")
let userinput = document.querySelector("#userinput")
btn.addEventListener("click",function(){
localStorage.setItem("userinput",userinput.value)
location.href = "index.html";
});
</script>
Then in index.html you can access that variable like below. The || "" says if userinput doesn't exist in localStorage, use "" as the default value;
<script>
let userInput = localStorage.getItem("userinput") || "";
</script>
CodePudding user response:
There are some ways through which this can be achieved.
- Using localStorage is one option. You can use the setItem and getItem functions in the settings.html and index.html respectively to get the value like so (on a high level):
localStorage["key"] = value;
... in another page ...
value = localStorage["key"];
jQuery load function. You can look into its documentation - pretty simple.
Through URI encoding as follows:
In the file from where you want to send:
var b = document.getElementById('name').value,
url = 'http://path_to_your_html_files/next.html?name=' encodeURIComponent(b);
document.location.href = url;
And in the file where you want to receive:
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];
}
All three options could be extended to work with multiple variables as well!
Hope it helps!