Temperature Converter is giving me NaN - javascript

I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.
This is what I have tried to do but it gives me NaN
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(this.value)">
<input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>

Your code is not working because in your #button1 you wrote:
onclick="temperatureConverter(this.value)"
where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".
To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".
Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.
Generally, it is not encouraged to use the same function to perform completely different actions.
function temperatureConverter(){
var input = document.getElementById('inputFahrenheit');
var value = input.value;
value = parseFloat(value);
var output = document.getElementById('outputCelcius');
output.innerHTML = (value - 32)/1.8;
}
function resetTemperature(){
/* clear the temperature */
console.log('clear');
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter()">
<input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>

Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">
<input id= "reset1" type= "reset" value= "Clear">
</p>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:
// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
function updateOutput(value) {
// make sure you do some checking to avoid XSS attacks.
document.querySelector('#output').innerHTML = value;
}
// keeps the form from submitting since we don't have an actual form handler and this is all front-end
document.querySelector('#converterForm').addEventListener('submit',(e)=>{
e.preventDefault();
});
document.querySelector('#convert').addEventListener('click', () => {
updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
});
});
function convertToCelsius(f) {
if(typeof f == 'string') f = parseFloat(f, 10);
if(isNaN(f)) {
throw new Error('Invalid parameter passed to function convertToCelsius');
}
return (f-32) * 5 / 9;
}
<form id="converterForm" action="/">
<input type="number" id="fahrenheit" placeholder="Fahrenheit value">
<input type="button" id="convert" value="Convert to Celsius">
<input type="reset" value="Clear">
<div id="output">
</div>
</form>
Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).

can't see you using any form.
your function,
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
then,
<form id="tempConverter">
Convert: <input type="text" id="unit" name="converter" />
<input
type="button"
value="Submit"
onclick="temperatureConverter(document.getElementById('unit').value);"
/>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.

Related

jquery - copy value of input from one form to another (form and input named the same)

I would like to copy the value from an input in one form to the value of an input(with the same name) of the next form down. The forms and inputs are named the same. All it needs to do is copy the value of the title input to the title input one form down.
<form>
<input name="file" value="1.xml">
<input name="title" id="title" value="Smith">
<input type="submit" id="copy-down" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title" value="Anderson">
<input type="submit" id="copy-down" value="copy">
</form>
etc...
In this case when the top "copy" button is clicked I would like jquery to overwrite Anderson with Smith.
$('#title').attr('value'));
Gives me Smith but I'm not sure what to do with that value once I have it.
Change HTML to this:
<form>
<input name="file" value="1.xml">
<input name="title" id="title1" value="Smith">
<input type="submit" id="copy-down1" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title2" value="Anderson">
<input type="submit" id="copy-down2" value="copy">
</form>
Javascript:
function copyHandler() {
var copyVal = document.getElementById("title1").value;
var replaceInput = document.getElementById("title2");
replaceInput.value = copyVal;
}
document.getElementById("copy-down1").onclick = function(){
copyHandler();
return false;
}
Some notes:
This is so straightforward in vanilla javascript that I didn't add the jQuery code.
You should never assign multiple elements to the same ID, class or name can be used for that purpose.
The return false; portion of the onclick function is necessary so that the form doesn't reload when you click your submit button.
Let me know if you have any questions.
you can try
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var GetNameAttr = $(this).find('input:nth-child(2)').attr('name');
var GetTitleValue = $(this).find('input:nth-child(2)').val();
var NextFormNameAttr = $(this).next('form').find('input:nth-child(2)').attr('name');
if(NextFormNameAttr == GetNameAttr){
$(this).next('form').find('input:nth-child(2)').val(GetTitleValue );
}
});
});
Note: this code will change the second input value in next form with
the second input value of form you click if the name is same .. you
can do the same thing with the first input by using :nth-child(1)
Demo here
if your forms dynamically generated use
$('body').on('submit','form', function(e){
instead of
$('form').on('submit', function(e){
for simple use I create a function for that
function changeNextValue(el , i){
var GetNameAttr1 = el.find('input:nth-child('+ i +')').attr('name');
var GetTitleValue1 = el.find('input:nth-child('+ i +')').val();
var NextFormNameAttr1 = el.next('form').find('input:nth-child('+ i +')').attr('name');
if(NextFormNameAttr1 == GetNameAttr1){
el.next('form').find('input:nth-child('+ i +')').val(GetTitleValue1);
}
}
use it like this
changeNextValue($(this) , nth-child of input 1 or 2);
// for first input
changeNextValue($(this) , 1);
// for second input
changeNextValue($(this) , 2);
Working Demo

Javascript max and min not working

I am trying to create a page that lets the user enter three numbers, and have the max and min values printed below from the input. I've used both the Math.max/min functions and also tried an if statement but When I click submit nothing shows up. Some insight would be greatly appreciated, thanks!
function max() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var z = document.getElementById("num3").value;
var maximum = Math.max(parseInt(x), parseInt(y), parseInt(z));
document.getElementById("max").innerHTML= maximum;
}
function min() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = parseInt(document.getElementById("num3").value);
document.getElementById("min").innerHTML = Math.min(x,y,z);
}
And here is my html
<p>Enter First Number:</p>
<input type="text" name = "number1" id="num1"><br>
<p>Enter Second Number</p>
<input type="text" name = "number2" id="num2"><br>
<p>Enter third number</p>
<input type="text" name = "number3" id="num3"><br>
<input type="submit" value="Submit" onclick="max(); min(); "><br />
<p>Max =</p><p id ="max"></p><br />
<p>Min =</p><p id ="min"></p><br />
replace <input type="submit"/> to <button type="submit" value="" onclick="minmax();">Submit</button>
and add JS function:
function minmax() {
min();
max();
}
Your problem seems related to how you are attaching your event.
It works OK when I use:
document.querySelector( '[type="submit"]' ).addEventListener( 'click', function() {
max();
min();
}, false );
http://jsfiddle.net/yemxrmqq/
You just need to change the tag related to the button, instead of:
<input type="submit" value="Submit" onclick="max(); min(); "><br />
just put:
<button type="submit" value="Submit" onclick="max(); min()">Click</button><br />
None of the answers here tell you why your code didn't work.
Identifiers in inline listeners are first resolved as properties of the element on which they are placed. Input elements have a default max attribute, so within an inline listener, the identifier max will reference the input's max property. Hence in any document:
<input onclick="console.log(max)">
shows '' (i.e. empty string).
So you can either change the names of the functions to something more meaningful, or change the context from which they are called so that the identifiers aren't resolved on the element, and the OP code works. e.g.
<input type="submit" value="Submit" onclick="callBoth()">
and
function callBoth() {
max();
min();
}
Incidentally, an input type submit outside a form is just a button, so you should use:
<input type="button" ...>

AJAX function not being called with button onclick function

I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.

retrieving text field value using javascript

I want to retrieve textfield value using javascript. suppose i have a code like:
<input type='text' name='txt'>
And I want to retrieve it using javascript. I call a function when a button is clicked:
<input type='button' onclick='retrieve(txt)'>
What coding will the retrieve function consist of?
You can do this:
Markup:
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="retrieve('txt');"/>
JavaScript:
function retrieve(id) {
var txtbox = document.getElementById(id);
var value = txtbox.value;
}
Let's say you have an input on your page with an id of input1, like this:
<input type="text" id="input1" />
You first need to get the element, and if you know the Id, you can use document.getElementById('input1'). Then, just call .value to get the value of the input box:
var value = document.getElementById('input1').value;
Update
Based on your markup, I would suggest specifying an id for your text box. Incase you don't have control over the markup, you can use document.getElementsByName, like so:
var value = document.getElementsByName('txt')[0].value;
One of the way is already explained by Andrew Hare.
You can also do it by entering the value in the textbox and getting a prompt box with entered message when a user click the button.
Let's say, you have a textbox and a input button
<input type="text" name="myText" size="20" />
<input type="button" value="Alert Text" onclick="retrieve()" />
The function for retrieve()
function retrieve()
{
var text = document.simpleForm.myText.value;
alert(text);
}

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