having trouble with javascript - javascript

Beginer to javasctipt. I am trying to write a simple calculation that will display some text if the time since oil change is past 6 months, the amount of oil left in the car is less then it started and finally display if everything is ok.
Thanks for the help
JavaScript
function oil(){
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.oil.result.write(aa);
}else{
document.oil.result.write("Everything Is all good");
}
}
HTML
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick = oil()>
<input name=result readonly>
</form>

There are a couple of problems with your code
Missing Form close tag
Your controls don't have IDs
missing quotes on the result input
Don't need to use a submit input when you're not submitting to a form. Try button
Not sure what document.oil.result.write(aa); will do. I think the correct process is to get the input using document.getElementById and then set the value of the control

I will try to answer your question with the least number of line changes. This is not the optimal answer. Comments have been added to help you understand required changes. Your HTML and JavaScript are invalid, so it was a surprise to me how they both ran on Chrome.
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function _oil(){ // oil() conflicts with your form's name
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.write(aa); // you can't .write() to an element
}else{
document.write("Everything Is all good");
}
window.event.preventDefault(); // so your window does not load the same page when you submit
return false;
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick ="_oil()"> <!-- you must enclose the onclick attribute, even if both work -->
<input name=result readonly>
</body>
</html>

May be like this:
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function oil(){
var start = document.getElementsByName("start")[0].value;
var lastOilChange = document.getElementsByName("time")[0].value;
var totalOil = document.getElementsByName("amount")[0].value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.getElementsByName("result")[0].value = aa;
}else{
document.getElementsByName("result")[0].value = "Everything Is all good";
}
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="thisform">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="button" value="go" onclick = oil()>
<input name=result readonly>
</form>
</body>
</html>
!!! The form name can not use oil

What you want is to set the value of the form field rather than trying to use write:
if( lastOilChange > 6 || start < totalOil){
document.oil.result.value = aa;
} else {
document.oil.result.value = "Everything Is all good";
}
As pointed out in other answers, though, you also need to prevent the form from trying to submit information to the server and reload the page. There are several ways of doing this (see e.g. JavaScript code to stop form submission). One is to replace the submit button with an ordinary button (<input type="button" value="Calculate" />).
Another is to attach your function to the form as an event handler, and return false at the end of it.
document.oil.onsubmit = function () {
...
return false;
}
(JSFiddle)

Related

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

Cant Get Answer Back In answer Box NAN is being shown

it does not returns prpoer answer it returnes NAN in Answer
<html>
<head>
<script type="text/javascript">
function pro(n,p)
{
var number=parseInt(n);
var powe=parseInt(p);
for(var i=1;i<powe;i++)
{
number*=number;
}
document.getElementById("answer").value=number;
}
</script>
</head>
<body>
<form name="F" >
Enter Number <input type="text" name="num" id="num"/>
Enter Power <select name="powe" id="powe">
<option value="2" >square</option>
<option value="3" >cube</option>
</select>
Answer<input type="text" name="Answer" id="answer" />
<input type="button" onClick="pro(num,powe)" value="Calculate" />
</form>
</body>
</html>
The issue is this: onClick="pro(num,powe)". Instead of the values for num and powe being gotten from the input elements and passed into the pro function, the actual element references (which are not numbers) are being passed.
To solve this problem, you'll need to get the values of the elements. But, before you just make a quick edit to your code, don't use inline HTML event attributes (onclick) in the first place. Instead, separate your JavaScript from your HTML and set up event handlers using modern standards with .addEventListener() as shown below.
Also (FYI):
Since you aren't actually submitting form data anywhere, you don't
need a <form> element.
It's not necessary to use parseInt with p.value because that
value is coming from your select and you've already set those at
whole numbers.
Don't bother with self-terminating tags (<input />) as you
gain nothing from using them.
If you are expecting only numeric input, it's better to use input
type=number which restricts the user input to numbers. Making this change also saves you from worrying about parseInt on the input number being misinterpreted as other bases than 10.
Since you don't want the user to be able to change the result of the
operation, it's better to display it in a non-editable element, like
a span.
It's a good idea to move your <script> element to just before the
closing body tag because, by the time the parser reaches that
point, all your HTML elements will have been parsed into memory.
<html>
<head>
</head>
<body>
<div>
Enter Number <input type="number" name="num" id="num">
</div>
<div>
Enter Power
<select name="powe" id="powe">
<option value="2">square</option>
<option value="3">cube</option>
</select>
</div>
<div>
Answer <span id="answer"></span>
</div>
<div>
<input type="button" value="Calculate">
</div>
<script>
// Get references to the inputs, the answer container and the button
let inputNum = document.getElementById("num");
let power = document.getElementById("powe");
let answer = document.getElementById("answer");
let btn = document.querySelector("input[type='button']");
// Set up the click event handler for the button
btn.addEventListener("click", function(){
// Now you need to get the input values and pass them
// to the function that will act with them
pro(inputNum.value, power.value);
});
function pro(n,p) {
var number = parseInt(n);
for(var i = 1; i < p; i++) {
number *= number;
}
answer.textContent = number;
}
</script>
</body>
</html>
Try
document.getElementById("answer").innerHTML = number

How to use a function in an external Javascript file in HTML?

This is my first time using an external Javascript file. I am doing the exercise in the murach series of books on Javascript and I am stuck on some pretty basic things. I will show the Javascript coding i did then i will show you the html file. Whenever I click the button to calculate the future value it does nothing even though I have the onload event handler.
/*Javascript*/
var $ = function(id) {
return document.getElementById(id);
};
function calculateFV(investment, interest, years) {]{
investment = $("investment").parseFloat($("investment").value);
interest = $("annual_rate").parseFloat($("annual_rate").value);
years = $("years").parseInt($("years").value);
var cInterest = investment * interest;
cInterest = parseFloat(cInterest);
futureValue = parseFloat(futureValue);
for (var i = 1; i < years; i++) {
investment = investment + (cInterest / 100);
}
investment = parseFloat(investment).toFixed(2);
$ ("future_value") = investment;
}
window.onload = function() {
$("calculate").onclick = calculateFV;
$("investment").focus();
};
/* End of Javascript */
/* HTML */
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1>Future Value Calculator</h1>
<label for="investment">Total Investment:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="annual_rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
/* End of HTML */
Regardless of the typographic errors in your code, there are some other mistakes you do I would like to mention:
parseInt() is a function; not a method. Therefore it must be used as a function. Like so: investment = parseFloat($("investment").value);
instead of:investment = $("investment").parseFloat($("investment").value);
$("future_value") is the textbox; not it's value. To actually have something appear in $("future_value"), you have to say: $("future_value").value = investment.
Your calculateFV() function should not have any parameters. Investment, interest and years are local variables inside the function, so your function doesn't require any input.
You parse too much and carelessly. In your code you say: cInterest = parseFloat(cInterest); and futureValue = parseFloat(futureValue);• We use parseFloat() to parse a string. The above variables contain arithmetic values that occurred after a mathematical operation and not strings. Therefore you do not need to parse them.
I created a jsFiddle with your code corrected and properly functioning. You can find it here.
Good luck in your learning process ☺

insert text to selected Textbox use Javascript

I have 2 textBox and 1 button!
I want to insert text to one of these textboxs. When I click to textbox_1 and click button, mytext will appear at textbox_1. When I click to textbox_2 and click button, mytext will appear at textbox_2.
How can I do this by using JavaScript?
Please help me! I'm new on JavaScript!
put id's of the two textboxes as textbox_1 and textbox_2 and put onclick='onCLickButton();' on the <button> tag
and write the following code in the script
var text_to_be_inserted = "sample";
function onCLickButton(){
document.getElementById("textbox_1").value='';
document.getElementById("textbox_2").value='';
if(document.getElementById("textbox_1").focused){
document.getElementById("textbox_1").value=text_to_be_inserted;
}
else if(document.getElementById("textbox_2").focused){
document.getElementById("textbox_2").value=text_to_be_inserted;
}
else{
// do nothing
}
}
Edited
Please accept my apologies actually I am used to use these functions as I have my own js file having these functions.
please add onfocus='onFocusInput(this);' in the <input> tags and add the following code in the script
function onFocusInput(object){
document.getElementById("textbox_1").focused=false;
document.getElementById("textbox_2").focused=false;
object.focused = true;
}
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts to text box when clicked the button";
function DisplayText(){
if(!index){
document.getElementById("txt1").value = text;
document.getElementById("txt2").value = "";
}
else{
document.getElementById("txt2").value = text;
document.getElementById("txt1").value = "";
}
index = index ? false : true;
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="button" value="Change Text" onclick="DisplayText()"/>
</body>
</html>
Take a look at the onFocus() attribute for the INPUT tag - and think about keeping track of what was last given the focus. I'm being a little vague as this sounds a lot like homework.
It isn't the prettiest / most delicate solution, but it works and you can build off it to fulfill your needs.
<script>
var field = 0;
function addText(txt){
if(field === 0) return false;
field.value = txt;
}
</script>
For a form such as
<form>
<input type="text" name="box1" id="box1" onfocus="field=this;" />
<input type="text" name="box2" id="box2" onfocus="field=this;" />
<input type="button" onclick="addText('Hello Thar!');" />
</form>

Calling Javascript from a html form

I am basing my question and example on Jason's answer in this question
I am trying to avoid using an eventListener, and just to call handleClick onsubmit, when the submit button is clicked.
Absolutely nothing happens with the code I have.
Why is handleClick not being called?
<html>
<head>
<script type="text/javascript">
function getRadioButtonValue(rbutton)
{
for (var i = 0; i < rbutton.length; ++i)
{
if (rbutton[i].checked)
return rbutton[i].value;
}
return null;
}
function handleClick(event)
{
alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="myform" onSubmit="JavaScript:handleClick()">
<input name="Submit" type="submit" value="Update" onClick="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
</body>
</html>
edit:
Please do not suggest a framework as a solution.
Here are the relevant changes I have made to the code, which results in the same behavior.
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye">;
<input name="Submit" type="submit" value="Update" action="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
You can either use javascript url form with
<form action="javascript:handleClick()">
Or use onSubmit event handler
<form onSubmit="return handleClick()">
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript: part
EDIT:
I just tried this code and it works:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
In this bit of code:
getRadioButtonValue(this["whichThing"]))
you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.
EDIT
To get the value out of the radio buttons, grab the JQuery library, and then use this:
$('input[name=whichThing]:checked').val()
Edit 2
Due to the desire to reinvent the wheel, here's non-Jquery code:
var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
if (document.myform.whichThing[i].checked==true) {
t = t + document.myform.whichThing[i].value;
}
}
or, basically, modify the original line of code to read thusly:
getRadioButtonValue(document.myform.whichThing))
Edit 3
Here's your homework:
function handleClick() {
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye" onSubmit="return handleClick()">
<input name="Submit" type="submit" value="Update" />
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.
In the function itself, I modified the how the form was being accessed. The structure is:
document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.
The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.
EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.
See the difference in this method:
function handleClick() {
alert("Direct Access: " + document.aye["whichThing"]);
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
return false; // prevent further bubbling of event
}
Pretty example by Miquel (#32) should be refilled:
<html>
<head>
<script type="text/javascript">
function handleIt(txt) { // txt == content of form input
alert("Entered value: " + txt);
}
</script>
</head>
<body>
<!-- javascript function in form action must have a parameter. This
parameter contains a value of named input -->
<form name="myform" action="javascript:handleIt(lastname.value)">
<input type="text" name="lastname" id="lastname" maxlength="40">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
And the form should have:
<form name="myform" action="javascript:handleIt(lastname.value)">
There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).
The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.
<!DOCTYPE html>
<html>
<head>
<title> Semester Results </title>
</head>
<body>
<h1> Semester Marks </h1> <br>
<script type = "text/javascript">
function checkMarks(total)
{
document.write("<h1> Final Result !!! </h1><br>");
document.write("Total Marks = " + total + "<br><br>");
var avg = total / 6.0;
document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
if(avg >= 90)
document.write("Grade = A");
else if(avg >= 80)
document.write("Grade = B");
else if(avg >= 70)
document.write("Grade = C");
else if(avg >= 60)
document.write("Grade = D");
else if(avg >= 50)
document.write("Grade = Pass");
else
document.write("Grade = Fail");
}
</script>
<form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
Semester 1: <input type = "text" id = "s1"/> <br><br>
Semester 2: <input type = "text" id = "s2"/> <br><br>
Semester 3: <input type = "text" id = "s3"/> <br><br>
Semester 4: <input type = "text" id = "s4"/> <br><br>
Semester 5: <input type = "text" id = "s5"/> <br><br>
Semester 6: <input type = "text" id = "s6"/> <br><br><br>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
Remove javascript: from onclick=".., onsubmit=".. declarations
javascript: prefix is used only in href="" or similar attributes (not events related)

Categories