Checking attribute value from a web page - javascript

I got attribute (capacity_gold) in a table of a web page. It is a marketplace so the values are constantly changing and I want to create a simple script which will alert me when the value of an attribute is greater than 100.
I found current value of an attribute in html table with id = "capacity_gold".
<td id="capacity_gold" class="center"></td>

Here I am implementing setInterval for 2 seconds;
<html>
<head>
<title>set Interval</title>
</head>
<body>
<div id="target">102</div>
</body>
<script type="text/javascript">
setInterval((checkTargetValue),2000);
function checkTargetValue() {
let targetValue = document.getElementById('target').innerHTML;
if (targetValue > 100) {console.log("crossed 100..")}
else { console.log("havent crossed yet"); }
}
</script>
</html>

Related

How to change an Id on another page as it loads through JavaScript

I want for the user to click a button which leads to another page. Depending on what button the user clicks, the page content should look different despite being on the same page. A simplified example is below:
Starting page html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Click Here
Click Here
<script src="script.js"></script>
</body>
</html>
second-page.html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="content-id">*CONTENT SHOULD BE LOADED HERE BASED OFF BUTTON CLICKED*</p>
<script src="script.js"></script>
</body>
</html>
script.js code:
function changeContent(n) {
document.getElementById("content-id").innerHTML = n;
}
The above code does not work. I'm guessing the browser doesn't see the content-id on the first page and fails to change anything before loading the second page. Any way to reference the right id on the right page using JavaScript (no jQuery) when the new page is loaded?
Short answer: there are several approaches, the easier that comes to mind is to use localStorage if you're dealing with same origin pages
What you need is to have user information available across multiple pages. So, unlike sessionStorage, localStorage allows to store data and save it across browser sessions:
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.
To use it, consider adapting your javascript of first page:
function changeContent(n) {
localStorage.setItem('optionChosen', n);
}
Then retrieve it in the second page's javascript.
var opt = localStorage.getItem('optionChosen')
var content = document.querySelector('#content-id')
if (opt == null) console.log("Option null")
if (opt === 'Option One') content.innerText = "Foo"
if (opt === 'Option Two') content.innerText = "Bar"
Edited -
Added 3 working examples that can be copy and pasted.
Problem -
Display content on a new view based on the button clicked to get to that view.
Approach -
You can store the value of ID in the browser to help identify the content that should be displayed in many ways. I will show you three working examples.
Notes -
I am over complicating this a little to show you how you might make this work since I do not know the exact circumstances you are working with. You should be able to use this logic to refactor for your requirements. You will find the following 3 solutions below.
1. Using GET Params
Uses the GET params in the URL to help you track necessary changes in your view.
2. Using Session Storage
A page session lasts as long as the browser is open, and survives over page reloads and restores.
Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Closing a tab/window ends the session and clears objects in sessionStorage.
3. Using Local Storage
The difference between localStorage and sessionStorage is the time the data persists. LocalStorage spans multiple windows and lasts beyond the current session.
The memory capacity may change by browser.
Similar to cookies, localStorage is not permanent. The data stored within it is specific to the user and their browser.
Solutions -
Working Examples - (Copy and paste any of the below solutions into an HTML file and they will work in your browser.)
Using GET Params
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
let currentURL = window.location.href.split("?")[0];
function appendParams(val) {
if (val === "a") {
window.location.assign(currentURL + "?id=a");
}
if (val === "b") {
window.location.assign(currentURL + "?id=b");
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="appendParams('a')">Click Here</button>
<button onclick="appendParams('b')">Click Here</button>
<p id="replace-id"></p>
</body>
</html>
<script type="text/javascript">
let url_str = window.location.href;
let url = new URL(url_str);
let search_params = url.searchParams;
let id = search_params.get("id");
document.getElementById("replace-id").id = id;
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("a").innerHTML = ContentOne;
}
if (id === "b") {
document.getElementById("b").innerHTML = ContentTwo;
}
</script>
Using Session Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
sessionStorage.setItem("id", "default");
function addSessionStorage(val) {
sessionStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = sessionStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addSessionStorage('a')">Click Here</button>
<button onclick="addSessionStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>
Using Local Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
localStorage.setItem("id", "default");
function addLocalStorage(val) {
localStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = localStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addLocalStorage('a')">Click Here</button>
<button onclick="addLocalStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>

how to get innerHTML value in javascript code

I want to change table <td> data by using innerHTML property. But after applying innerHTML property those values set in <td> are not accessible in Javascript code.
So is there any alternative to innerHTML property so that value can be set in <td> and it can also be accessed in Javascript Code.
Javascript code
<script>
var row=0,col=0,i=1;//can be used in loop
document.getElementById("tableID").rows[row].cells[col].innerHTML=i;
</script>
Look at this small sample, innerHTML works. Walk with cursor keys through the Table. Show us more Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table key´s</title>
<style>
td{width:40px;height:40px;background:#ddd;}
</style>
</head>
<body>
<div id="tableContainer">
</div>
<script>
var aktRow=aktCol=4,max=9;
tableContainer.innerHTML = '<table id="mt">'+('<tr>'+'<td></td>'.repeat(max+1)+'</tr>').repeat(max+1)+'</table>';
mt.rows[aktRow].cells[aktCol].style.background='#f00';
window.addEventListener("keyup", function(e){
var colDiff, rowDiff;
var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
if (keyMap.has(e.keyCode)){
mt.rows[aktRow].cells[aktCol].style.background='#ddd';
mt.rows[aktRow].cells[aktCol].innerHTML=aktRow+'-'+aktCol;
console.log(mt.rows[aktRow].cells[aktCol].innerHTML);
[colDiff,rowDiff]=keyMap.get(e.keyCode);
aktRow+=rowDiff;
aktCol+=colDiff;
aktRow = (aktRow>max) ? max : (aktRow < 0) ? 0 : aktRow;
aktCol = (aktCol>max) ? max : (aktCol < 0) ? 0 : aktCol;
mt.rows[aktRow].cells[aktCol].style.background='#f00';
}
})
</script>
</body>
</html>
your code is wrong here
.rows[row].cells[col]
This is what i suggest:
set an id for each cell, something like col1row1 as id, then access the cell by id:
document.getElementById("col1row1").innerHTML = i
or have a for loop go through each row and cell with getElementsByType('td').innerHTML = i for example
take a look at this :
Iterating through a table with JS

javascript returns NaN in additition

I am trying to calculate total number of links click by user. To do so i am using following code
<html>
<head>
<script type="text/javascript">
function fnc()
{
document.getElementById("atext").innerHTML="tested";
var iStronglyAgreeCount=parseInt (document.getElementById("ISA") );
document.getElementById("ISA").innerHTML=iStronglyAgreeCount +1;
}
</script>
</head>
<body>
<label id="atext" onClick="fnc()">I strongly agree</label> (<span><label id="ISA">0</label></span>)
</body>
I am storing starting number 0 into a variable and trying to add 1 at each click.But it shows NaN.
Use .textContent to get the text content of the element.
function fnc() {
document.getElementById("atext").innerHTML = "tested";
var iStronglyAgreeCount = parseInt(document.getElementById("ISA").textContent);
document.getElementById("ISA").innerHTML = iStronglyAgreeCount + 1;
}
<a href="#">
<label id="atext" onClick="fnc()">I strongly agree</label>
</a>(<span><label id="ISA">0</label></span>)
Note: If target browser is <IE9, consider using Polyfill

Passing a var to another page

Is it possible to pass the totalScore var to another page onclick so that it can be displayed there? ex: click submit link it goes to yourscore.html and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});
Let we suppose that your HTML may be as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#process").click(function() {
var totalScore = 0;
/*
Your code to calculate Total Score
Remove the next line in real code.
*/
totalScore = 55; //Remove this
alert("Total Score = "+totalScore);
$("#submit-link").attr('href',"http://example.com/yourscore.html?totalScore="+totalScore);
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="process">Process</button>
<br />
Submit Total Score
</body>
</html>
Check out this DEMO
In yourscore.html you may able to know more in the following queation to extract the URL parameter from the URL:
Parse URL with jquery/ javascript?
This is generally done by changing the url of the page. i.e. if you are going go to a new page, just do:
http://example.com/new/page?param1=test
If the page already exists in a new window (like a popup that you own), set the url to something new:
http://example.com/new/page#param
Open a window:
var win = window.open('http://example.com/new/page?totalscore'+totalscore,'window');
Change the location:
win.location.href='http://example.com/new/page?totalscore'+totalscore;
Other ways of doing this could be websockets or cookies or localstorage in HTML5.
if you are aiming to support more modern browsers the elegant solution could be to use sessionStorage or localStorage! Its extremely simple and can be cleared and set as you need it. The maximum size at the low end is 2mb but if your only storing INTs then you should be okay.
DOCS:
http://www.html5rocks.com/en/features/storage
http://dev.w3.org/html5/webstorage/
DEMO:
http://html5demos.com/storage
EXAMPLE:
addEvent(document.querySelector('#local'), 'keyup', function () {
localStorage.setItem('value', this.value);
localStorage.setItem('timestamp', (new Date()).getTime());
//GO TO YOUR NEXT PAGEHERE
});

JavaScript display new page when submit HTML form

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.

Categories