Using javascript functions in HTML - javascript

I am creating a small webpage that will add two input fields together and place the result in another input field. This is what I have:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function add(){
var num1 = parseInt(document.calc.num1.value);
var num2 = parseInt(document.calc.num2.value);
var answer = (num1+num2);
document.getElementById('res').value = answer;
}
</script>
</HEAD>
<BODY>
<FORM NAME="calc">
<INPUT TYPE ="button" NAME="add" Value="+" onClick="add()">
<hr/>
<INPUT TYPE ="text" NAME="num1" Value="">
<INPUT TYPE ="text" NAME="num2" Value="">
<hr/>
<INPUT TYPE ="text" ID="res" NAME="result" VALUE="">
</FORM>
</BODY>
</HTML>
And I am getting the following error when I press the + button.
Uncaught TypeError: object is not a function

Try changing the function name from add to addNumbers or something like that.

onclick is the right attribute to handle click

onClick="add()"
Switch this bit to
onclick="add()"

The problem is the name of the function "add()", change the name and you will see that it will works!

HTML
<p>
<label for="field1">Field 1</label>
<input type="number" id="field1"/>
</p>
<p>
<label for="field2">Field 2</label>
<input type="number" id="field2"/>
</p>
<p>
<label for="total">Total</label>
<input readonly type="number" id="total"/>
</p>
<p>
<input type="button" id="calc" value="Calculate"/>
</p>
Javascript
Goes in a script tag in head.
function sumFields(fields) {
var total = 0;
// goes through each field and adds them to the total
for(var i=0,l=fields.length; i<l; i++)
{ total += parseInt(document.getElementById(fields[i]).value); }
document.getElementById('total').value = total;
}
function calc_click() {
// runs when the button is clicked
sumFields(['field1','field2']);
}
// main function
function init() {
// add button functionality
document.getElementById('calc').addEventListener('click',calc_click,false);
}
// fires when the DOM is loaded
document.addEventListener('DOMContentLoaded',init,false);

Related

ask user enter name with Javascript and html

I have code to ask the user to enter their name and display it in a <p> element
function my() {
var x = document.getElementById("tt").textContent;
document.getElementById("demo").innerHTML = x;
}
<h1> Whats your name ? </h1>
<form method="POST">
<input type="text" id="tt" placeholder="Enter Name : ">
<input type="checkbox" checked>
</form>
<button onclick="my">Submit now</button>
<p id="demo"></p>
</div>
i expect the output will be print name of user
2 items:
An input element doesn't have textContent, it has a value.
When delcaring an onclick handler, include the parenthesis () to indicate it's a function call.
function my() {
var x = document.getElementById("tt").value;
document.getElementById("demo").innerHTML = x;
}
<h1> Whats your name ? </h1>
<form method="POST">
<input type="text" id="tt" placeholder="Enter Name : ">
<input type="checkbox" checked>
</form>
<button onclick="my()">Submit now</button>
<p id="demo"></p>
</div>
You are having some syntax errors in code. Missing (), properties of input context.
function display(){
console.log('here')
document.getElementById("demo").innerHTML =document.getElementById("tt").value;
}
<h1> Whats your name ? </h1>
<form name = "myForm">
<input type="text" name = "name" id="tt" placeholder="Enter Name : ">
<input type="checkbox" checked>
</form>
<input type="submit" onclick="display()">
<p id="demo"></p>
</div>
</body>
To learn about syntax and javascript.
You should use the value property rather than the textContext property. input type fields use value and have no textContent.
Additionally, your onclick is incorrectly defined. I recommend using javascript:myFunction() format, when executing a function in this manner. See below:
function my() {
var x = document.getElementById("tt").value;
document.getElementById("demo").innerHTML = x;
}
<h1> Whats your name ? </h1>
<input type="text" id="tt" placeholder="Enter Name : ">
<input type="checkbox" checked>
<button onclick="javascript:my()">Submit now</button>
<p id="demo"></p>
You'll notice I also removed the form node. If you don't preventDefault on a form it will refresh the page upon submit.
It's fine for this kind of thing to just not use a form tag. But if you wanted to keep it, you'll want to select it and preventDefault behavior like this:
var myForm = document.querySelector('form');
myForm.addEventListener('submit', function(e) {
e.preventDefault();
});
You missed the round brackets:
<button onclick="my()">Submit now</button>

Converting a value using JavaScript

Somehow my below JavaScript code to convert the value from kilometers to nautical mile doesn't seem to work. It seems very simple but I could not find out why I am. I would appreciate your help.
<div class="calculator">
<form>
Enter a value in Kilometers:
<input type="text" id="kM" value="1000"> Result in Nautical Mile:
<input type="text" id="nM" value="" disabled>
<button onclick="return calculate();" id="calculate">CALCULATE</button>
</form>
</div>
<script>
function convert(kiloMeter) {
return kiloMeter / 1.852;
}
function calculate() {
var kMeter = Number(document.getElementById("kM").value);
var convertedValue = convert(kMeter);
document.getElementById("nM").innerHTML =
convertedValue;
return false;
}
</script>
There are at least two issues causing your script to not work
Input elements don't have an innerHMTL property. They have a value. So document.getElementById("nM").innerHTML should be document.getElementById("nM").value
At that point everything should be fine. You shouldn't need to change your button type to button since you return false from the function and the button returns false to the form, stopping the form from submitting. HOWEVER there appears to be an issue with naming your function calculate (at least in Chrome and Firefox) the same as the id of the element (id="calculate"). Changing the name of the function or the id fixes the issue.
function convert(kiloMeter) {
return kiloMeter / 1.852;
}
function calculate() {
var kMeter = Number(document.getElementById("kM").value);
var convertedValue = convert(kMeter);
document.getElementById("nM").value = convertedValue;
return false;
}
<div class="calculator">
<form>
Enter a value in Kilometers:
<input type="text" id="kM" value="1000"> Result in Nautical Mile:
<input type="text" id="nM" value="" disabled>
<button onclick="return calculate();" id="xcalculate">CALCULATE</button>
</form>
</div>
For input tag you should use value rather than innerHtml. You do not need to return false also.
<div class="calculator">
<form>
Enter a value in Kilometers:
<input type="text" id="kM" value="1000"> Result in Nautical Mile:
<input type="text" id="nM" value="" disabled>
<button type='button' onclick="calculate()" id="">CALCULATE</button>
</form>
</div>
<script>
function convert(kiloMeter) {
return kiloMeter / 1.852;
}
function calculate() {
var kMeter = Number(document.getElementById("kM").value);
var convertedValue = convert(kMeter);
document.getElementById("nM").value =
convertedValue;
}
</script>
You should use value instead of innerHTML:
document.getElementById("nM").value = convertedValue;

Calculating two fields in a form using JavaScript with a submit button and reset button

Here the code that I made and not working looking to see how I would get my sum into the result field, Also looking how to make a reset button to clear all the text from the fields.
JSBin.
<html>
<head>
<script>
function addition() {
var x = +document.getElementById('num1').value;
var y = +document.getElementById('num2').value;
document.getElementById('result').value = x + y;
document.result.submit()
}
function reset() {}
</script>
</head>
<body>
<header>
<h1>Calculator Using Forms & JavaScript</h1>
</header>
<form>
Number 1:
<input type="number" id="num1" value="0" autofocus>
<br> Number 2:
<input type="number" id="num2" value="0">
<br> Result:
<input type="text" id="result" value="0" readonly>
<br>
</form>
<input type="button" onclick="addition()" value="addition">
</body>
</html>
Why do you want to submit the form?
You can use document.forms. to access the form.
Try this:
<html>
<head>
<script>
function addition() {
var x = +document.getElementById('num1').value;
var y = +document.getElementById('num2').value;
document.getElementById('result').value = x + y;
document.forms.calculator.submit()
}
function reset() {
document.forms.calculator.reset();
}
</script>
</head>
<body>
<header>
<h1>Calculator Using Forms & JavaScript</h1>
</header>
<form name="calculator">
Number 1:
<input type="number" id="num1" value="0" autofocus>
<br> Number 2:
<input type="number" id="num2" value="0">
<br> Result:
<input type="text" id="result" value="0" readonly>
<br>
</form>
<input type="button" onclick="addition()" value="addition">
<input type="button" onclick="reset()" value="reset">
</body>
</html>
Do you want this one?
jsbin
<html>
<head>
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<script>
function addition() {
var x = +document.getElementById('num1').value;
var y = +document.getElementById('num2').value;
document.getElementById('result').value = x + y;
//document.result.submit()
//if you want use submit, use this code. if only see the result, don't use this
//Submit is receive data, so you can't see a result.
//document.getElementById('formId').submit();
//jquery submit
//$("form")[0].submit();
}
function reset() {
//no jquery
document.getElementById('formId').reset();
//jquery
//$("form")[0].reset();
}
</script>
</head>
<body>
<header>
<h1>Calculator Using Forms & JavaScript</h1>
</header>
<form id="formId">
Number 1:
<input type="number" id="num1" value="0" autofocus>
<br> Number 2:
<input type="number" id="num2" value="0">
<br> Result:
<input type="text" id="result" value="0" readonly>
<br>
</form>
<input type="button" onclick="addition()" value="addition">
<input type="button" onclick="reset()" value="reset">
</body>
</html>
Note that forms can be submitted without clicking the submit button, so if you want something to happen on submit, attach a listener to the form's submit handler. To reset a form only requires a reset button, no code.
Form controls must have a name to be successful and submit their value with the form, and you can pass a reference to the form using this from the listener so you don't need to use getElementById.
Implementing the above significantly reduces the amount of code required.
In the following, the submit listener returns false so prevents the form from submitting. If you want the form to submit, just remove the return statement from the in–line listener:
function addition(form) {
form.result.value = +form.num1.value + +form.num2.value;
}
<form name="calculator" onsubmit="addition(this); return false;">
Number 1:
<input type="number" name="num1" value="0" autofocus>
<br> Number 2:
<input type="number" name="num2" value="0">
<br> Result:
<input type="text" name="result" value="0" readonly>
<br>
<input type="submit" value="Submit form">
<input type="reset">
</form>
You may not want to submit the form at all, in that case you can make the submit button a plain button and call the function from there, but remember to stop the form submitting otherwise.
just give an id to the form and in your reset function, just do
document.getElementById("myForm").reset();
updates:
according to ROBG's comments, you don't need to bind a function to the button.
you can simply add a
<input type="reset">
to reset all fields of the form, and if the button is out the form, you can do
<input form="formID" type="reset">
to associate to specific form.

Why my adding of two numbers does not work?

I managed to resolve this issue with a different method but i still don't understand why this method didn't work in the first place, i am probably missing something:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
*{padding: 10px}
</style>
</head>
<body>
<script type="text/javascript">
function adding(){
var addnum1=parseInt(num1);
var addnum2=parseInt(num2);
var result=addnum1 + addnum2;
sum.value=result;
}
</script>
<input type="text" name="num1"><br>
<input type="button" value="+" disabled="true"><br>
<input type="text" name="num2"><br>
<input type="button" value="=" onclick="adding()"><br>
<input type="text" name="sum">
</body>
</html>
Here is a example of a jsfiddle that you can use to learn better.
https://jsfiddle.net/pxpmp45v/2/
JavaScript:
function adding(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var addnum1=parseInt(num1);
var addnum2=parseInt(num2);
var result= addnum1 + addnum2;
var sum = document.getElementById('sum');
sum.value=result;
}
Your HTML:
<input type="text" id="num1"><br>
<input type="button" value="+" disabled="true"><br>
<input type="text" id="num2"><br>
<input type="button" value="=" onclick="adding()"><br>
<input type="text" id="sum">
Few things to note while retrieving value and assigning to a textbox:
You must use getElementById method and assign a id attribute to your element.
<input type="text" id="num1">
You must also retrieve the value of that element in your JavaScript otherwise you will get a NaN. Use this document.getElementById('num2').value instead of document.getElementById('num2')
Debugging help: Try console.log which prints your variables to your browsers console thus helping you identify what is wrong.
While I have seen people accessing the values of inputs directly as global variables it not recommended. I would suggest using getElementsByName to access the values.
function adding(){
document.getElementsByName("sum")[0].value =
parseFloat(document.getElementsByName("num1")[0].value) +
parseFloat(document.getElementsByName("num2")[0].value);
}
<input type="text" name="num1"><br>
<input type="button" value="+" disabled="true"><br>
<input type="text" name="num2"><br>
<input type="button" value="=" onclick="adding()"><br>
<input type="text" name="sum">
num1, num2, and sum aren't declared in your javascript.
You could give them IDs like
<input type="text" id="num1">
<input type="text" id="num2">
<input type="text" id="sum">
And then access them with document.getElementById()
function adding(){
var addnum1 = parseInt(document.getElementById('num1').value);
var addnum2 = parseInt(document.getElementById('num2').value);
var result = addnum1 + addnum2;
document.getElementById('sum').value = result;
}

How to set sum value on text feild when second value is set text?

This is my demo cord.
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
// Add them together and display
var sum = parseFloat(my_input1) + parseFloat(my_input2);
document.getElementById('total').value=sum;
}
I want to work this function when my_input2 is enter it's value. Just like onclick method for button is there any event to set value to total tetxfeild after key release event?
<script type="text/javascript">
$(document).ready(function () {
$("#my_input2").blur(function () {
var sum = parseInt($("#my_input1").val()) + parseInt($("#my_input2").val());
$("#total").val(sum);
});
});
</script>
<div>
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" />
</div>
And also u should frame ur question correctly bcz u have added code in button click and asking us it should work after leaving textbox
Put onkeyup() on second input field this will fire your function.
Something like that:
<input type="text" id="my_input2" onkeyup="doMath();" />
try this
<input type="text" id="my_input2" onchange="doMath();" />

Categories

Resources