I'm trying to transfer data from one html page to another page, so I wrote this program:
page1.ejs:
<a href="/events" onclick="send()">
<span class="message">
new alert
</span>
</a>
function send() {
$mesg = $('.message');
var msg = $mesg.text();
var msg1 = msg.replace(/\s/g, '');
localStorage.setItem("message", msg1);
}
page2.ejs:
<script src="socket.io/socket.io.js"></script>
<script>
document.getElementById("event").innerHTML = localStorage.getItem("message");
</script>
<td id="event"></td>
But I don't get the data transferred from the pages? what is my mistake?
The issue is in page2.ejs:
Problem: The HTMLElement <td id="event"></td> is not yet available when your <script> block is parsed and executed, so document.getElementById("event") returns undefined.
Solution: Move the <script> block to the bottom, beneath <td id="event"></td> and it should work.
page1.ejs:
On click of submit -
window.location.href="page2.ejs.html?text1="+$('#text1').val()
page2.ejs:
$(document).ready(function(){
var value1 = document.URL.indexOf('?text1=');//value from pag1.ejs
});
you should define the Send() function inside script tag
and Page 2 run the java script when page ready
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("event").innerHTML = localStorage.getItem("message");
});
Related
I am dynamically generating table rows uing javascript for loop:
<script>
var data = planData();
for(var i=0;i<data.length;i++){
document.write("<tr data-toggle=\"modal\" data-target=\"#mapModel\">");
document.write("<td>"+data[i]['id']+"</td>");
document.write("<td>"+data[i]['sender']+"</td>");
document.write("<td>"+data[i]['receiver\r']+"</td>");
document.write("<td>"+data[i]['carrier']+"</td>");
document.write("<td>"+data[i]['arrivalTimeEnd']+"</td>");
document.write("<td> 10hrs </td>");
document.write("<td> <i class=\"fa fa-circle-o text-success mr-2\"></i> Delivered </td>");
}
</script>
After that I want to store the clicked row values in variable and I am able to do it by using below code in msg variable:
<script>
var msg;
//add event listener to table rows
let thetable = document.getElementById('mytable').getElementsByTagName('tbody')[0];
for (let i = 0; i < thetable.rows.length; i++)
{
thetable.rows[i].onclick = function()
{
TableRowClick(this);
var coords = document.getElementById('output').value;
};
}
function TableRowClick(therow) {
msg = therow.cells[0].innerHTML+'*'+therow.cells[1].innerHTML+'*'+therow.cells[2].innerHTML+'*'+therow.cells[3].innerHTML+'*'+therow.cells[4].innerHTML+'*'+therow.cells[5].innerHTML;
document.getElementById('output').innerHTML=msg;
};
</script>
Now the problem is, when I tried to use msg variable in which data is stored(in same html file but in another div tag), I am not able to use it.
<div>
<script>
document.write(msg)
</script>
<div>
Output: Undefined
You can only share the data between different script tag or files if we make the variables global or save them to browser storage.
You can save the message to window.
window.msg = 'your message';
You can access this variable in any file or script tag. but you have to make sure you are reading value after writing it.
Browser Storage, you can use any of localStorage, sessionStorage, cookieStorage.
but you have to make sure you are clearing these variables.
The msg access can be after it's definition, if you access before definition it will give you undefined. Below is the example.
<head>
<script>
var msg = "hello"
</script>
<script>
(function() {
console.log(msg);
})();
</script>
</head>
<body>
Test
</body>
I am trying to create an IE11 compatible webpage which will sit on a few users desktops, which will grab some data from a JSON API and display it.
The user will type in their individual API key before pressing a button, revealing the API data.
Could you please help where my code has gone wrong? The error message I get from the console is: "Unable to get property 'addEventListener' of undefined or null reference. " So it looks like it is not even making the call to the API.
<script>
var btn = document.getElementById("btn");
var apikey = document.getElementById("apikey").value
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://example.example?&apikey=' + document.getElementById("apikey").value);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
document.getElementById("title").textContent = ourData.data[0]["name"];
}}}
);
</script>
.
<body>
Enter API key: <input type="text" id="apikey">
<button id="btn">Click me</button>
<p id="title"></p>
</body>
The API data which I am trying to just extract the name from, looks something like this:
{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}
It's likely that you're including the Javascript in the page before the HTML. As Javascript is executed as soon as the browser reaches it, it will be looking for the #btn element which will not have been rendered yet. There are two ways to fix this:
Move the Javascript to the bottom of the <body> tag, making it run after the HTML has been output to the page.
Wrap the Javascript in a DOMContentLoaded event, which will defer the script until the page has finished loading. An example is as follows:
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn');
var apikey = document.getElementById("apikey").value;
[...]
});
Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>
I have a MainView "About.cshtml" it has a script tag in it and a partial view.
<script>
$(function () {}
</script>
<div>
#Html.Partial("~/Views/Maps/_MapDetailsList.cshtml", Model.saVM)
</div>
Inside "_MapDetailList.cshtml" partial view i am referencing another script ge.js
#Scripts.Render("~/Scripts/ge.js")
<table id="MapDetails">
.....
<tr><th>
<script>setGrowthArray(1, 1);</script>
</th></tr>
</table>
ge.js
var dictionaryGrowth = new Array();
function setGrowthArray(colIndex, mapDetailId) {
//making a sparse array
dictionaryGrowth[colIndex] = mapDetailId;
}
Now i want to send this dictionaryGrowth array to server side after the page/table is loaded
so i did the following in the About.cshtml script but didnot work..
<script>
$(function () {
$("#MapDetails").load(function () { alert("everything seems fine");});
}
</script>
Also please tell me what will be the script and DOM loading sequence in my case.
UPDATE
Probably the Current sequence is
Script on About.cshtml is executed
ge.js is executed
document.ready inside partial view is fired
javascript function (setGrowthArray) from inside DOM is called
Now i want to call my controller??
If i write window.onload = ... inside ge.js it is never fired
You can substitute using $.post() for .load(), pass result of setGrowthArray(1, 1) as data posted to server
<script>
$.post("/path/to/server", {growth:setGrowthArray(1, 1)}, function(data) {
console.log(data); // response from server
$("#MapDetails").html(data);
})
</script>
I'm trying to handle translations with Mustache.js and it works fine for some part of the code but not for another part.
<script>
function MyFunction() {
// If a submit button is pressed, do some stuff and run this function to display the result
var tmpText = "";
tmpText = "<b>{{someTextInJSfunction}}</b>"; // this is NOT OK
document.getElementById("totalText").innerHTML = tmpText;
}
</script>
</head>
<body>
<div id="sampleArea">
</div>
<script id="personTpl" type="text/template">
<span id="totalText"></span></p>
<b>{{ImpNotice}}</b> {{Contact}} // this is OK
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/mustache.js"></script>
<script>
$( document ).ready(function() {
var lang = 'en_us';
$.getJSON('json/'+lang+'.json', function(data) {
var template = $('#personTpl').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
});
</script>
When I click a Submit button, my JS function is called and depending on some calculation, some text should be displayed in the page. This is the part that doesn't work, {{someTextInJSfunction}} is displayed instead of the actual content of {{someTextInJSfunction}}.
The content of {{ImpNotice}} and {{Contact}} is correctly displayed because I assume the variables are located in the <script id="personTpl"> tags.
I'm not sure how to fix it for the variables located in my JS functions, such as {{someTextInJSfunction}}.