Passing javascript variable from one html page to another page - javascript

Hello All i started working on html recently,but iam struck in this situation where i want to send a value from one html page to the next html page just like,how websites shows our name after sign up success.Here i have written two html pages with,
pageOne.html
<!DOCTYPE html>
<head>
<title>
Home
</title>
<meta charset="UTF-8">
</head>
<style>
.myP{
color: lightgreen;}
</style>
<body>
<p id="p1" class="myP" onclick="myFun()">DataSend</p>
</body>
<script>
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
localStorage.setItem("message", textprevi);
window.open("pageTwo.html","_self");
}
</script>
</html>
and my second
pageTwo.html
<!DOCTYPE html>
<html>
<body onload="fun">
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
}
</script>
</html>
But when i tried the above solution,the element with id = "tBox" was empty but i wanted it to be filled with value = "DataSend" which is from pageOne.html.
Please help me with the promblem.
Thanks in advance.

The problem is with this line
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
Here tBox is a an input element. So you have to use value instead of innerHTML
document.getElementById("tBox").value= localStorage.getItem("message");

You can do it using querystring parameters
In page one:
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
window.open("pageTwo.html?data=" + textprevi,"_self");
}
In page 2
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var data = getParameterByName('data');

You made two mistakes in pageTwo.html.
<!DOCTYPE html>
<html>
<body onload="fun()"><!-- You didn't invoke the function here -->
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").value = localStorage.getItem("message"); // You need to set the value for input fields, not innerHTML.
}
</script>
</html>
These changes should make your code work.

Related

Greet User by name using Javascript and query string

I am trying to get the user's name from a form input and display it on the page in the form of a greeting "Hello (user)".
I have already got the solution to do it in 2 separate HTML files but I need to do it all in one file using query string and onload options.
Thanks for your help!
firstpage.html
<input type="text" id="titletxt">
<button onclick="Submit()">Submit</button>
<script>
function Submit() {
let name = document.getElementById("txtname").value;
window.location.href = "secondpage.html?" + name;
}
</script>
secondpage.html
<html>
<head>
<title>Test</title>
<script>
function loadTitle() {
let queryString = window.location.search.split('?')[1];
document.write("<h2>Hello "+queryString+"</h2>")
document.title = "hello "+queryString;
}
</script>
</head>
<body onload="loadTitle()">
</body>
</html>
Change your secondpage.html body to:
<body onload="loadTitle()">
<script>
function loadTitle() {
const queryString = window.location.search;
const name = new URLSearchParams(queryString).get("name");
document.body.innerHTML = "<h2>Hello " + name + "</h2>";
document.title = "hello " + name;
}
</script>
</body>
If I am correct in believing that you wanted all of the code to be in one file, I have a solution for you.
Solution with search params:
It simply checks if there is a search parameter called 'name' and if there is is replaces everything with Hello [name].
<html>
<head>
<title>Hello</title>
</head>
<body>
<input type="text" id="titletxt">
<button onclick="Submit()">Submit</button>
<script>
function loadTitle() {
const queryString = window.location.search;
const name = new URLSearchParams(queryString).get("name");
if (name) {
document.body.innerHTML = "<h2>Hello " + name + "</h2>";
document.title = "Hello " + name;
}
}
document.body.onload = loadTitle;
function Submit() {
let name = document.getElementById("titletxt").value;
window.location.search = "?name=" + name;
}
</script>
</body>
</html>

How do I select text between two characters in Javascript?

So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))

Pass jquery variable to iframe src

I want to pass the value which i get from a text box to the src of my iframe. I am using the following code to get the value from textbox, on the button click it should be passed to the iframe src and replace the query:'*' with the variable passed, i.e. the * should be replaced.
How to proceed with this?
Foloowing is the iframe with html code
<iframe src="http://localhost:5601/#/dashboard/New-Dashboard?embed&_a
=(filters:!(),panels:!((col:1,id:env,row:1,size_x:4,size_y:3,type:visualization)
,(col:5,id:env-2,row:1,size_x:4,size_y:3,type:visualization),(col:9,id:env-3,
row:1,size_x:4,size_y:3,type:visualization)),query:(query_string:(analyze_wildcard:
!t,query:'*')),title:'New%20Dashboard')&_g=(refreshInterval:(display:Off,pause
:!f,section:0,value:0),time:(from:now%2Fy,mode:quick,to:now%2Fy))" height="600"
width="800" id="myframe"></iframe>
<!DOCTYPE html>
<html>
<head>
<title>jQuery With Example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.btnGetName').click(function (event) {
var name = $('.txtName').val();
alert(name);
});
});
</script>
</head>
<body>
<div>
<input type="text" class="txtName" value="hello" id="querypass"/><br />
<button class="btnGetName">Get Name</button>
</div>
</body>
</html>
Try this
var src = $('#myframe').attr('src');
var newSrc = src.replace("query:'*'", "query:'" + name + "'");
$('#myframe').attr('src', newSrc);
You can try following code:
Note: Assuming that your <iframe> is within same HTML document:
$('.btnGetName').click(function (event) {
var name = $('.txtName').val();
alert(name);
var iframeObj = $("#myframe");
var srcString = iframeObj.attr("src");
srcString = srcString.replace("query:'*'","query:'"+name+"'");
iframeObj.attr("src",srcString );
});
Please make sure that you don't put single quote in your text field.

How to pass a variable in match function in javascript?

Firstly this may sound like a duplicate question but I was unable to resolve my problem using the previous asked questions:
This is my HTML page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function test() {
var totalids='XYZ##';
var variable_name=document.getElementById('p1').value.replace(/^\s+|\s+$/g,'');
var result = totalids.match(/variable_name/i);
if (result){
alert('Matched');
} else {
alert("Not Matched");
}
}
</script>
</head>
<body>
<input type="button" value="click on me" onclick="test()">
<input type="text" value="xyz" id="p1">
</body>
</html>
This program is not matching my String.I want to match my string using case-insensitive match.I know the problem lies in this line:
var result = totalids.match(/variable_name/i);
I am unable to pass variable in match function.I can do this;
var re = new RegExp(str1, "g");
But I don't know how to do cases-insensitive search using above line.
Here is how:
var re = new RegExp(str1, "gi");

dynamically adding form elements in javascript in IE/Mozilla

So, I have tried bunch of things but didn't founded a workaround with this
I have this code this works fine on Chrome. But it does't work on mozilla or IE, In the console it doesn't shows up any error. It just doesn't work.
<?php
echo"<script>alert('okay');</script>";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
</head>
<script type="text/javascript" LANGUAGE="JavaScript1.3">
function name3() {
var abc = document.createElement("FORM");
//abc.setAttribute("method","POST");
abc.method = "POST";
abc.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
/*a.setAttribute("type","text");
a.setAttribute("name","a");
a.setAttribute("value","abc");*/
a.name = 'a';
a.value = "abc";
abc.appendChild(a);
abc.submit();
}
</script>
<input type = "button" onclick = "name3();" value = "click">
</html>
Instead of a.name, I have also tried using a.setAttribute but still didn't work
Please help!!! Thanks :)
You should append form to body and then latter removed it once posted. Currently you are not adding your form to DOM. it actually need to be in the DOM to be sent in a page load.
Complete Code
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript">
function name3() {
var form = document.createElement("FORM");
form.method = "POST";
form.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
a.name = 'a';
a.value = "abc";
form.appendChild(a);
//Apend form to body
document.getElementsByTagName('body')[0].appendChild(form);
//Submit form
form.submit();
// But once the form is sent, it's useless to keep it.
document.getElementsByTagName('body')[0].removeChild(form);
}
</script>
</head>
<body>
<input type="button" onclick="name3();" value="click" />
</body>
</html>
You should add the new element to the DOM tree first and then submit the form. If you do not want display them you can add styles to hide the elements.
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
</head>
<script type="text/javascript">
function name3() {
var abc = document.createElement("FORM");
//abc.setAttribute("method","POST");
abc.method = "POST";
abc.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
/*a.setAttribute("type","text");
a.setAttribute("name","a");
a.setAttribute("value","abc");*/
a.name = 'a';
a.value = "abc";
abc.appendChild(a);
document.getElementById("body").appendChild(abc);
abc.submit();
}
</script>
<body id="body">
<input type = "button" onclick = "name3();" value = "click">
</body>

Categories

Resources