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
Related
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>
I'm making a small website as a test. Very new to JavaScript and HTML forms so I thought i'd throw myself into what I consider to be the deep end and give it a go.
I'm trying to get an interger to be displayed on the page, that is the result of a few calculations.
I want to find the difference between the first number (current value), and the second number (desired value) and then divide that number by 25 and store that as a variable. I then want to display that variable inside a message.
My current HTML :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
My current JavaScript :
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
You are 99% there. All you have to do is change
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
into
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
The way you had it, those variables just held the HTML (technically, DOM) elements themselves, and not the values that were in them. This gets the values and then turns them into integers so you can do math with them. If you do this, your site do exactly what you want it to do.
Be careful:
var currentRating = document.getElementById("currentRating").value;
is a String (text) value... to be sure of int value you can do
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
If you like to display result in page you can use a DIV with and id and do:
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
hope this code will help :
html :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript :
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
Subtract first field from the other, and if the value is not greater than 0 multiply by -1.
Divide that by 25.
My HTML:
<html>
<head>
<title>Circles!</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="math.js"></script>
</head>
<body>
<div id="header">
<h1>The area of a circle given the circumfrence</h1>
</div>
<div id="group">
<input type="text" id="input">
<label>Circumfrence</label>
<button type="button" id="button">Calculate</button>
</div>
<div id="answerbox"><span id="answer"></span></div>
</body>
</html>
and my js:
$( document ).ready(function() {
$("#button").click(function() {
var input = $("#input").val;
var answer = (((input * input) * Math.PI) * 0.25);
$(answer).append("#answer")
$("#answerbox").fadeIn(700);
});
});
So the 'answer' value wont display in my 'answer' span, which is inside my 'answerbox' div. What is wrong here?
You must use correct the val and append in code:
Correct:
$( document ).ready(function() {
$("#button").click(function() {
var input = $("#input").val(); // changed added '()'
var answer = (((input * input) * Math.PI) * 0.25);
$("#answer").append(answer); // changed exchaned answer #answer
$("#answerbox").fadeIn(700);
});
});
You wrote the code in reverse order:
$(answer).append("#answer") // wrong
$('#answer').append(answer) // right!
Plus you made a mistake calling .val, it needs the parenthesis since that is a function:
var input = $("#input").val();
Part One, val
val is a function
http://api.jquery.com/val/#val1
Your current code is assigning the function to the variable input.
To call the function and retrieve the content of the input field, you need to call the function using parentheses.
var input = $("#input").val();
Part Two, append
append takes the content to add as a parameter.
http://api.jquery.com/append/
You must first use the CSS selector syntax to choose where to append the content, then pass the content.
$("#answer").append(answer);
I'm learning JavaScript and I'm wondering why something like:
document.getElementById('partofid'+variable+number) doesn't work?
Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one.
HTML:
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
JS:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+counter+1);
alert(nextDiv); // why does it return null
alert('div-'+counter+1); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
Try using parseInt:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));
The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.
Demo
What's going on here is Javascript has some strange rules about types and the + operator.
string + anything means convert anything to string, then concatenate them together. So "foo" + "bar" == "foobar"... and "div" + 1 == "div1".
The the next step, addition is done left to right, so "div" + 1 + 1 goes to "div" + 1 == "div1".
"div1" + 1... remember, convert to string then put together, so we get "div1"+ 1 == "div11".
I would put parenthesis around your arithmetic. "div" + (1+1) would do the right hand side thing first, so (1+1) == 2 as you expect, then "div" + 2 == "div2", so that's what you expect.
As to the alert thing, your first one is looking at the result of the element lookup, and the second one is looking at the string itself. So the first is null because the element lookup didn't find anything.
This code results in string concatenation. E.g. if counter is 1, then you will get div-11
'div-'+counter+1
This is because addition is resolved from right to left.
Then you try to retrieve element with id div-11, but you don't have html element with such an id. That's why the function getElementById returns null.
To solve the problem first add counter to 1 and then join it with div, like this 'div-'+(counter+1)
Because counter+1 = 11 => id = div-11 is not exist. Try this:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+Number(counter+1));
alert(nextDiv); // why does it return null
alert('div-'+Number(counter+1)); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
it does work and does exactly what you asked it to do but since you do not have a div-11 there is nothing found so the evaluation returns null.
if you want div-2 then simply use order of operations to sum the counter to the number:
Fiddle
Here is your answer:
<html>
<head>
<script>
function load()
{
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+(counter+1));
//alert(nextDiv); // why does it return null
//alert('div-'+(counter+1)); // while this doesn't?
nextDiv.style.display = "block";
counter++;
},true);
}
</script>
</head>
<body onload="load()">
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
</body>
<html>
To solve this kind of returning "null" values by getElementById("").
you can use script inside the body instead of head it will return the html element.
const m=document.getElementById('one')
const m1=document.getElementById('demo')
console.log(m1);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo">sample text</p>
<script src="script.js"></script>
</body>
</html>
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
});