Let's say I have <div id="mydiv>>111</div> in html
and I want to get this number by using GetElementbyID(myid).value and convert it to integer
I have tried ParseInt, ParseInt(x, 10), Number(x)....
They all returned NaN. Why?
Note: It works if the number is in a text field, but I want to take it from a div in body.
Change :
document.getElementById("mydiv").value;
To :
document.getElementById("mydiv").innerHTML;
Example :
<html>
<head>
<style>
</style>
</head>
<body>
<div id="mydiv">111</div>
<script>
var txt = document.getElementById("mydiv").innerHTML;
var num = parseInt(txt);
alert(num);
</script>
</body>
</html>
Related
I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari
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
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.
I want to write a script that multiplies any number in a text field with itself by the push of a button and gives the result as an alert.
I'm completely new to Javascript (and have to write my first exam later today).
The syntax is killing me, sometimes so similar to Java, but than again not.
Here's what I came up with so far:
<!DOCTYPE html>
<html>
<head>
<script>
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
You'll want to make sure you parse the input value as it will be a string when you query for it. To operate on it using multiplication, you need a number. You'll usually want to pass 10 as the second radix parameter as there are different implementations of parseInt
function myMultiply() {
var x = parseInt($('#num1').val(), 10);
var y = x*x;
alert(x + " times " + x + " equals " + y);
return false;
}
You cant multiply string it will be concatenated, parse value to int using parseInt first
parseInt
function myMultiply()
{
var x= parseInt($('#num1').val(), 10);
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
try replacing var y=x*x; with var y=Number(x)*Number(x);
Along with other answers indicating you should parseInt it should be noted that you aren't currently including jQuery (which gives you access to the $(".element") notation).
jQuery is a very common javascript library that saves a lot of time for very common Javascript tasks (selectors, events etc). You'll see the $() notation in many tutorials and to use it you need to include jQuery.
This will work:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function myMultiply()
{
var x= parseInt( $('#num1').val(), 10 );
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1" />
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
Your code is fine. You are simply missing the jquery include.
Add <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> right above your other script and everything works unchanged.
Javascript will parse strings and convert them to numbers automatically when it sees that you are trying to multiply. "4" * "2" is 8, not "44" or "42" or any other magical combination. You have a syntax error by referring to $ without actually including jQuery as a required script, so the function ends up being undefined.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
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>