HTML input into Javascript - javascript

I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button

Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.

I think you mean:
var r = document.getElementById("radius").value;

getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);

Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;

You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.

Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.

Related

Pig Latin translator using a While Loop in Javascipt

My son is teaching himself JavaScript. (He’s too young to have an account here.) He’s trying to write a Pig Latin translator using a “while loop.” The basic question he right now is how to sequence the code - so the user types in the word, then the program translates it, then the result appears in the alert box. He’s brand new to this, so if anyone has any friendly feedback it would be much appreciated.
Here’s what he’s got:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="Javascript">
<!-- Beginning of JavaScript -
</SCRIPT>
</HEAD>
<BODY bgcolor="Blue">
<h3> Type some text then click TRANSLATE. </h3>
<FORM>
<INPUT NAME="wordToTranslate" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="TRANSLATE" onClick="alert(form.wordToTranslate.value)" style="font-size:1em;background:lime">
</FORM>
<script>
while (wordToTranslate.substring(0, 1) = bcdfghjklmnpqrstvwxyz) {
console.log(var wordWithoutFirstLetter = wordToTranslate.slice(0, 1);
var wordWithoutLastLetters = wordToTranslate.slice(1) var wordToTranslate = wordWithoutFirstLetter + wordWithoutLastLetters;
++
wordToTranslate + ay
</script>
Oh my, there are a lot of errors in this code. I would really recommend trying some easier examples first. But to save you some time in the future, here are (some) of the issues I see in your JavaScript. Every one of these will cause an error and stop the code from running.
The primitive strings are not inside quotation marks or apostrophes (for instance, bcdfghjklmnpqrstvwxyz should be "bcdfghjklmnpqrstvwxyz")
Attempting to log syntax rather than a string (or object that can be converted to a string): console.log(var ...) will cause an error
Using an increment (++) operator on a string variable...
some parentheses are missing closing parentheses, and the curly bracket has not closing curly bracket
you never actually get the string to use from the HTML element (i.e., the "value" of the <INPUT>).
After working with some easier examples first and building up to this, I would suggest googling a JavaScript pig latin example and using it as a reference to learn the more complicated concepts (like matching the first letter to a consonant). Good luck!
Since you're looking for general help, I would gently suggest that if he's learning JavaScript and HTML that he learn the newer versions, namely HTML5 , ES6+, and CSS3.
Below is essentially what he has so far--Pig Latin translation code not included--but moved to the newer standards.
'use strict';
const btnTrans = document.getElementById('btnTrans');
const txtWord = document.getElementById('txtWord');
btnTrans.addEventListener('click', translate);
function translate() {
console.log(txtWord.value);
}
body {
background-color: blue;
}
button {
font-size: 1em;
background:lime
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<input name="wordToTranslate" id="txtWord" type="text">
<button type="button" id="btnTrans">Translate</button>
</form>
</body>
<script src="script.js"></script>
</html>
Note the DOCTYPE on the html. Also, all of the HTML elements are lowercase and the attribute values are quoted. JavaScript side, the event listener for the button click event is wired up in the JavaScript code, not in the HTML. The variables are set using const, which is scoped differently than var. I've also moved the inline styles to a CSS file and gotten rid of the old, deprecated ones like bgcolor.
Separating the code into separate files like this creates a clear responsibility for each part of the overall app: the HTML is the view; the CSS styles that view and can be overridden or changed in the future; the JavaScript acts as the controller.
I don't really expect this to be selected as the answer to this question; rather, it's general advice for a general question and new-to-the-web-world programmer. Welcome aboard! =)

Cannot get the hidden tag value

Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.

Making an HTML game-ish thing

So I'm using Notepad++ with HTML and javascript to try and make a little clicker game (Similar to cookie clicker if you've ever played it) and I'm just using it to experiment with stuff. I have a uneditable text field and a button that when clicked adds "1" to the value of the textfield. I've been trying to create another button that simply checks for a value greater or equal to five in the text field, then subtract five if it's true. (The ultimate goal is to have three buttons -- One that when clicked checks for a value greater than five, then subtracts five, which makes another button that wasn't clickable become clickable, which will add 10 to the value when clicked kind of like an upgrade.)
I've got the button to add +1 to the value, and I've been trying to get the upgrade one to enable a disabled button. But for some reason the button won't work..
<!DOCTYPE html>
<html>
<head>
<title>Button Clicker</title>
<script language="Javascript">
function handleButtonClick() {
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
// Add one
currentValue = currentValue + 1;
// Put it back with the new +1'd value
textField.value = currentValue;
}
function handlebuttonclick() {
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
// Minus one
currentValue = currentValue - 1;
// Put it back with the new -1'd value
textField.value = currentValue;
}
</script>
</head>
<body>
<script language="Javascript" type="text/javascript">
function enable(){
if (document.form="upgrade".clicked==''){
document.agreement_form.clicker.disabled=true
}else{
document.agreement_form.clicker.disabled=false
}
}
</script>
<button type="button" form="upgrade" onclick="enable()" onclick="handlebuttonclick"/>Upgrade</button>
<br>
<button type="button" onClick="handleButtonClick()"/>Press here</button>
<input type="button" value="Clicker" disabled name="clicker">
<input type="text" value="0" id="textField" readonly/>
</body>
</html>
Here's the bug:
<button type="button" form="upgrade" onclick="enable()" onclick="handlebuttonclick"/>Upgrade</button>
^ ^
| |
\ /
\ /
\ /
\ /
you can't have two onclick handlers
The solution is to simply call both functions in the onclick handler:
onclick="enable();handlebuttonclick()"
Or even call enable from inside handlebuttonclick:
function handlebuttonclick() {
// ..... bunch of code
enable();
}
BTW, some advice:
Try not to confuse yourself by declaring variables and functions with similar names (handlebuttonclick vs handleButtonClick). Just because it works doesn't mean it's "correct". The primary function of source code is to document your intentions. Making the code execute on a computer is actually a secondary function. Give your functions meaningful names:
<button id='increment' onclick='handle_increment()'> + </button>
<button id='decrement' onclick='handle_decrement();enable()'> - </button>
Secondly, and this is minor but since it means less typing and cleaner code it's good to follow: language="javascript" is deprecated and I believe is invalid for HTML5 (which is your DOCTYPE) and type="text/javascript" is unnecessary for HTML5. So just write
<script>
// javascript code...
</script>
Thirdly, self-closing tags like <input ... /> is xHTML and is invalid HTML5 (though browsers will tolerate it, potentially triggering quirks mode (quirks mode is a mode where the browser tries to emulate previous bugs)). Also, you've incorrectly self-closed the <button> tag. The /> at the end of the tag has the same meaning as closing the tag with a </...> tag. So:
<button />
means the same as
<button></button>
Therefore, <button /></button> is invalid.
But that's moot anyway since this is html5 and not xhtml - don't use the />.
There are lots of other things that can be improved such as assigning onclick handler in javascript rather than HTML etc. but they're not strictly "wrong", they're more a matter of style.

Why is my named form not being returned?

In the following code, I get an error
cannot read property "Area Sorted" of undefined
when I call the line
document.SortingForm.AreaSorted.value = Names.join("\n");
I've been over the code a hundred of times and I don't see why this is happening. I would really appreciate any help with this.
sort.html
<!doctype html>
<html>
<title>Sort</title>
<head>
<script type="text/javascript" src="sort.js">
</script>
</head>
<body>
<h1>Sorting String Arrays</h1>
<p>Enter two or more names in the field below,
and the sorted list of names will appear in the
text area.</p>
<form name=”SortingForm”>
Name:
<input type="text" name="FieldWord" size="20" />
<input type="button" name="ButtonAddWord" value="Add" onClick="SortNames();" />
<br/>
<h2>Sorted Names</h2>
<textarea name=”AreaSorted” cols=”60” rows=”10” >
The sorted names will appear here.
</textarea>
</form>
</body>
</html>
sort.js
var Names = new Array();
function SortNames()
{
Name = document.getElementsByName("FieldWord")[0].value;
Names.push(Name);
Names.sort();
document.SortingForm.AreaSorted.value = Names.join("\n");
}
You have weird speechmarks around the name of the form: ”. I'm a little suprised that using these is not valid though.
Why don't you try adding an id to the textarea and use:
document.getElementById('AreaSorted');
That should always work, regardless of the form being there.
Also the quotes before and after the form's name seem to be off, try retyping them.
I don't know where that syntax originates from, but obviously it doesn't work (any more). To get references to forms by their name, you should use document.forms.
document.forms.SortingForm.elements.AreaSorted.value = names.join("\n");
But the recommended way would be to assign an id to the input, and use document.getElementById.
AreaSorted isn't an id .. so either use
document.getElementByName('AreaSorted')[0]
or
.. give your element an id and use document.getElementById, which I would recommend.

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

Categories