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>
Related
I am learning some more JavaScript and am having trouble getting a temperature conversion exercise to run.
The below is what I've written so far with the code commented out being a formula from an earlier exercise I did from my instruction book.
Here's the code:
<!--
Challenge:
Write a function to take a temperature in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Hour 2.
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
document.write ("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write ("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
</body>
</html>
-->
<html>
<head>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
</script>
</head>
<body>
<script>
function conversion(a, b) {
var a = 10;
var b = hTemp;
alert (conversion);
}
</script>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Right now when I run the code is displays all the code of the conversion function but doesn't actually convert!
I have been going through this for hours and I feel like the right answer isn't too far away. My question in a nutshell: What do I need to correct to get this to run properly?
Help would be appreciated as I am keen to keep coding but have hit a brick wall here.
You have written alert(conversion), which will basically display the function code, since conversion is a reference to the function.
One other thing, your conversion function takes two variables a and b which is unnecessary as you are not passing any parameters while calling it.
Here is what you can do:
<html>
<head>
<script>
function conversion() {
let cTemp =40; // temperature in Celsius
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
</script>
</head>
<body>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Since you are learning, you should start using best practices. Avoid var for variable declaration and use let instead, as it is block scoped. Instead of using alert you can also use console.log to print values in developer console. I would advise you to search for some tutorials on Google Chrome Developer Tools.
There are several problems with your solution:
You are passing a function to the alert and not the result of the function.
In Javascript you can pass around functions as variables. So if you do alert(conversion), you tell the browser to show the actual function code to the user.
To execute the function, you put parantheses after the function name:
alert(conversion());
You are declaring argument for your function but not using them
Your function is
function conversion(a, b) { …
But you call the function without arguments conversion(), you could call it with arguments like this:
<input type="button" value="Click for Conversion" onclick="conversion(40,10) " />
You are overwriting your arguments without using them
But you will see that nothing changes by adding these numbers, it is because you overwrite them in your function anyway a = 10; b = hTemp. Also if you want to convert a temperature you only should have one input variable. So let us rewrite your function:
function conversion(cTemp) {
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
So now then function accepts an argument called cTemp and then puts out the conversion. You can now call the function with different arguments like this:
<input type="button" value="Click to convert 40 C" onclick="conversion(40) " />
<input type="button" value="Click to convert 50 C" onclick="conversion(50) " />
Or even better, you can do a prompt:
function promptForConversion() {
let cTemp = prompt("Temperature in Celsius");
conversion(cTemp);
}
<input type="button" value="Click to convert number" onclick="promptForConversion(50) " />
These are very basic principles, I highly recommend to do some more tutorials, that also teach you how to organize your code in reusable functions. Good luck!
How do you create a function in Javascript which, given a number, returns how many hundreds fit into that number - and then rounds to 2 decimal places?
The code I have:
function howManyHundreds(num) {
return (num / 100.00);
}
However, it just returns solid numbers. For ex. 55/100 = 0, instead of .55.
The assignment suggests using the modulo operator (%) to help, but I am unsure how to use that for rounding to 2 decimal places, not just the remainder.
Calling your function here displays .55 in alert box:
<!DOCTYPE html>
<html>
<head>
<script>
function howManyHundreds(num) {
return (num / 100.00);
}
</script>
</head>
<body>
<script>
alert(howManyHundreds(55));
</script>
</body>
</html>
If you want to use the mod operator you could do something like this:
(100 % .55 = .45)
<!DOCTYPE html>
<html>
<head>
<script>
function howManyHundreds(num) {
var mod = 100.00 % num
return mod.toFixed(2)
}
</script>
</head>
<body>
<script>
alert(howManyHundreds(.55));
</script>
</body>
</html>
The function you have looks valid and returns the value you are expecting.
How ever this is how I tested opening Chrome Console and define below steps and you can verify the output.
step 1 : caller = {};
step 2 (in case you want to fix the output by 2 decimals : caller.execute = function howManyHundreds(num) {
return Number((Number(num) / 100.00).toFixed(2));
}
step 2 (in case you want to round the output) : caller.execute = function howManyHundreds(num) {
return Math.round((Number(num) / 100.00).toFixed(2));
}
step 3 : caller.execute(3444); // Test your output.
Hope this helps.
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>
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.