I am unable to get the function AreaT() to verify and validate the entered value in the input box as the answer to the area of a triangle.
I keep getting "wrong" message even for the correct answer.
What am I doing wrong?
Thank you for taking the time to check my code.
<html>
<head>
<script>
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
var area = getElementById("area");
function AreaT(){
document.getElementById('height').value = height;
document.getElementById('base').value = base;
if(area== 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
</script>
</head>
<body>
<form>
<h2>HEIGHT:</h2><input type="button" size="20" id="height"/>
<h2>BASE: </h2><input type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input type="text" size="20" id="area"/>
<input type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</form>
</body>
</html>
Try this:
HTML
<body>
<h2>HEIGHT:</h2><input type="button" size="20" id="height"/>
<h2>BASE: </h2><input type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input type="number" size="20" id="area"/>
<input type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</body>
Javascript (put in <header> tag)
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
document.getElementById('height').value = height;
document.getElementById('base').value = base;
function AreaT(){
var area = document.getElementById("area").value;
if(area == 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
Adding on to what was already mentioned, you need to add a .value to the area element as well. I also changed the input type of AREA to number.
Change getElementById("area") to document.getElementById("area").value. You also need to assign area from inside your AreaT() function, otherwise it's not gonna get the value that the user typed in.
Also, your javascript needs to be below those form elements, otherwise it can't "see" them and you will get undefined values.
Related
I have created 5 input text boxes using HTML and made a button while clicking the button the values will print the result input text box. The first 4 fields are my inputs and the last text field is my output. unable to debug the issue. kindly find the code and help to find the issue.
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(h+w+g+t);
document.getElementById('result').innerHTML=total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2"id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<!--
<p
id="result">
</p>
-->
<button id="btn" onClick="JS()">Calculate</button>
There are two keys to resolving your issue:
Coerce your inputs to numbers, which I'm doing by adding a + in front of the value assignments. If you don't do this, your values may be treated like strings and concatenated rather than added like numbers.
Set the value of the input element, not the innerHTML. If you'd rather use a <p> element, which it appears you commented out in your sample code (and which I restored for completeness of my answer), consider using innerText.
See example here:
function JS() {
var h = +document.getElementById('h').value;
var w = +document.getElementById('w').value;
var g = +document.getElementById('g').value;
var t = +document.getElementById('t').value;
let p_result = document.getElementById('p_result');
var total = (h + w + g + t);
document.getElementById('result').value = total;
p_result.innerText = total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2" id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<br>
<p id="p_result" style="color:red;"></p>
<br>
<button id="btn" onClick="JS()">Calculate</button>
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(Number(h)+Number(w)+Number(g)+Number(t));
document.getElementById('result').value =total;
}
.value instead of .innerHTML
also, you should convert inputs values to number cause instead of making the sum will be as consider them string( for example if you type 1 , 2 , 3 , 4 without converting to number will be 1234 if you convert to number will be 10
How would I implement NaN and have Inavlid input display in a element
To do this I have to use isNaN to verify that numerical values are input.
I just want it to display "Invalid input" whenever a non numeric value is put in either of the two first text boxes.
http://jsfiddle.net/hq3m1uns/1/ this is my fiddle link
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Question2</title>
<style>
</style>
<script type="text/javascript">
window.onload = function(){
};
function add_number(){
var first_number = document.querySelector("#tb1").value;
var second_number = document.querySelector("#tb2").value;
var First = parseInt(first_number);
var Second = parseInt(second_number);
var result = First + Second;
document.getElementById('tb3').setAttribute("value",result);
}
</script>
</head>
<body>
<div>
<h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1">
<br> Enter Second Number : <br>
<input type="text" id="tb2" name="TextBox2">
<br> Result : <br>
<input style="width: 50%" type="text" id="tb3" name="TextBox3" >
<br>
<input onclick="add_number()" type="button" id="b1" value="GO" />
</body>
</html>
Just add a paragraph tag in your HTML file with id "msg" and do the following changes in your javascript code.
function add_number() {
var first_number = document.querySelector("#tb1").value;
var second_number = document.querySelector("#tb2").value;
if (isNaN(first_number) || isNaN(second_number)) {
document.getElementById('msg').innerHTML = "Invalid Input";
} else {
document.getElementById('msg').innerHTML = "";
var First = parseInt(first_number);
var Second = parseInt(second_number);
var result = First + Second;
document.getElementById('tb3').setAttribute("value", result);
}
}
<p id="msg"></p>
One way is to use a keyup event listener on the input field to validate the numeric value and update the textContent of the paragraph element based on its validity.
Another solution is to use a input type="number" for the input and use HTML5's checkValidity/reportValidity on it, but I'll leave that for you to research and learn about on your own.
function validate(inputId, helpId) {
var value = document.getElementById(inputId).value;
var help = document.getElementById(helpId);
if (isNaN(value))
help.textContent = "invalid input"
else
help.textContent = ""
}
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1" onkeyup="validate('tb1', 'help1')">
<p id="help1"></p>
I can't figure out why this function is not working. Assignment instructions call for the javascript function code to be in it's own javascript file.
Here is the html
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="submit" id="submit" value="Calculate BMI" />
</form>
Here is the function based on that form. It's supposed to calculate the bmi.
function calcBMI() {
var weight = parseInt(document.getElementByID("weight").value);
var height = parseInt(document.getElementByID("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result').value;
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
3 things:
getElementById must be in camel case. Not with capital D's at the end
Reference to textbox should be just var textbox = document.getElementById('Result') and not with .value at the end.
Button's type should be button otherwise the form is being posted.
Your working example:
function calcBMI() {
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="button" id="submit" value="Calculate BMI" />
</form>
1.
At a glance it seems as though you are not preventing the default browser behaviour, you need to use event.preventDefault() to prevent the form submitting.
function [...](e) {
e.preventDefault();
[...]
}
2.
Ensure you DOM has loaded before manipulation begins by loading the JavaScript below the HTML or you can make use of the DOMContentLoaded event.
3.
A sanity check, ensure that the script has been loaded using the <script></script> tags. If it is an external file, use the src property, if it is just code, wrap it in the aforementioned tags.
4.
You need to change the usage of getElementById you have used getElementByID instead of the lowercase d in Id.
5.
When you are doing textbox.value = result; what you are actually doing is textbox.value.value = result; as you have referenced it as .value originally.
Finally,
Make use of the console as it'll have saved you from asking here as the errors are thrown in them.
There are few problems with your function:
You have a typo in document.getElementByID, it should be document.getElementById
You have to pass an event object into your function, and invoke preventDefault, so that your form won't be submitted to the server
the line:
var textbox = document.getElementById('Result').value;
it should be
var textbox = document.getElementById('Result');
So overall, your function should look like:
function calcBMI(e) {
e.preventDefault();
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
Use on click event, change your getElementByID to getElementById and change the type to button and not submit. Submit would post it but what you need is to call the function.
<input type="button" id="submit" value="Calculate BMI" onclick="calcBMI()"/>
In your javascript change
var textbox = document.getElementById('Result').value
To
var textbox = document.getElementById('Result').value = result;
And remove
textbox.value = result;
You made a mistake here in weight and heightIt should be in camel case only.
document.getElementById("your id")
and also why not you check in console what error it shows
I have a simple HTML page that has a text field, a button, and a div.
I want to have a user input a stock symbol into the field. When they push submit button, an image of a graph will display inside the div.
The graphs already exist #http://ichart.finance.yahoo.com/w?s=
To get a graph for a paticular symbol, I need to add the symbol, an '&', and a large random number. This is a working example
http://ichart.finance.yahoo.com/w?s=YHOO&1234567890
I am not able to make the symbol, the &, and the random number append to the end of the URL. I am also not sure if I am using form correctly.
Here is the code:
function changeChart() {
var rand_no = Math.random();
rand_no = rand_no * 100000000;
var sym = document.myform.symbol.value;
document.getElementById('divService').innerHTML = '<' + 'object id="foo" name="foo" type="text/html" data="http://ichart.finance.yahoo.com/w?s="' + sym + '"&"' + rand_no + '"><\/object>';
}
<form name = "myform">
<p>
Enter stock symbol
<input id="Text1" type="text" name="symbol"/>
<input type="button" value="Go" name="Submit" onclick="changeChart(this); return false;"/>
</p>
<div id="divService">
<object id="foo" name="foo" type="text/html" data="http://www.aol.com/"></object>
</div>
Here is the complete code, The CSS wouldn't display properly on here.
https://docs.google.com/document/d/1pq39BKxWRqDS162jWss7-fvTbr0r28wq4VFiedh8SCY/edit?hl=en
I checked just some minutes ago and it seems there's no need for &1234567890-like part of URL, so I'd change the code to get this:
function changeChart() {
var sym = document.forms[0].elements['symbol'].value;
var divContent = '<'+'object id="foo" name="foo" type="text/html" data="http://ichart.finance.yahoo.com/w?s=' + sym +'"/>';
document.getElementById('divService').innerHTML = divContent;
}
Given that random number is not necessary, and in HTML code:
<form name = "myform">
<p>
Enter stock symbol
<input id="symbol" type="text" name="symbol"/>
<input type="button" value="Go" name="Submit" onclick="changeChart(); return false;"/>
</p>
<div id="divService">
<object id="foo" name="foo" type="text/html" data="http://www.example.com/"></object>
</div>
</form>
Note that now id has the same value as name for text input, and removed this argument for function call. I hope this helps you. (Update: Tested OK on jsFiddle and here is result)
When you make a random number using Math.random, Javascript returns a double. When you put that random number into the URL, you want it to be a string. Try changing the first line of changeChart to this:
var rand_no = String(Math.random() * 1000000);
Maybe I've been working on my site for to long, but I can't get the following to work. I am having my textarea fire an onkeyup() event called limiter which is supposed to check the textarea and limit the text in the box, while updated another readonly input field that shows the amount of characters left.
This is the javascript code:
<script type="text/javascript">
var count = "500";
function limiter(){
var comment = document.getElementById("comment");
var form = this.parent;
var tex = comment.value;
var len = tex.length;
if(len > count){
tex = tex.substring(0,count);
comment.value =tex;
return false;
}
form.limit.value = count-len;
}
</script>
The form looks like this:
<form id="add-course-rating" method="post" action="/course_ratings/add/8/3/5/3"
accept- charset="utf-8"><div style="display:none;"><input type="hidden"
name="_method" value="POST" />
//Other inputs here
<div id="comment-name" style="margin-top:10px">
<div id="comment-name-text">
<b>Comments</b><br />
Please leave any comments that you think will help anyone else.
</div>
<style type="text/css">
.rating-form-box textarea {
-moz-border-radius:5px 5px 5px 5px;
}
</style>
<div class="rating-form-box">
<textarea name="data[CourseRatings][comment]" id="comment"
onkeyup="limiter()" cols="115" rows="5" ></textarea>
<script type="text/javascript">
document.write("<input type=text name=limit size=4
readonly value="+count+">");
</script>
</div>
<input type="submit" value="Add Rating" style="float: right;">
</form>
If anyone can help that would be great.
You have:
onkeyup="limiter()"
Since you aren't calling limiter in the context of an object, you are calling window.limiter.
var form = this.parent;
So this is window and form is window.parent, which is the same as window (unless the document is loaded in a frame).
You want to make this the form control. Do this using event binding in unobtrusive JavaScript.
(And don't use an input as an element solely for displaying output, it does not make sense. You probably want to use a label associated with the textarea … and to use another label for <b>Comments</b><br />Please leave any comments that you think will help anyone else.)
Would this work for your? Example Link
EDIT:
You should pass the element instance with the function call onkeyup="limiter(this)" this way in your function you'll have a reference to the object that called this function, now your function will be something like:
function limiter(a) {
var comment = a;
var form = document.getElementById('add-course-rating');
var tex = comment.value;
var len = tex.length;
if (len > count) {
tex = tex.substring(0, count);
comment.value = tex;
return false;
}
form.limit.value = count - len;
}
Also no need to create element dynamically if you don't really need that! so just set the value of the readonly with Javascript:
<input type="text" name="limit" id="limit" size="4" readonly value="">
<script type="text/javascript">
var limit = document.getElementById('limit');
limit.value = count;
</script>
And you are good to go!