I have problems with a simple bit of code. I'm trying to take a value from an input field and then do a simple calculation. The calculation is supposed to take place with an onSubmit command and then append it to a p tag.
HTML:
<h1 class="titleHead">Calculator</h1>
<form method="POST" action="#" onSubmit="depositCal()">
<input type="text" name="money" id="money">
<input type="submit" value="How much" onSubmit="">
</form>
<div>
<p class="answer"></p>
</div>
Javascript:
$(document).ready(function() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
function depositCal() {
$('.answer').append(finalNumber);
}
})
I get back function not defined when it runs.
I know this is probably very simple but any help would be greatly appreciate.
Try this:
Give your form a name and ID e.g. 'myForm'
JS
$('#myForm').submit(function(e){
e.preventDefault();
var numberOne = $('#money').val();
var numberTwo = 4;
var finalNumber = numberOne + numberTwo;
$('.answer').append(finalNumber);
});
e.preventDefault() - stops the form from submitting (thus refreshing the page) and the function is only fired when submit is clicked.
Addition
numberOne is getting it's value from a form field so it sees it as a string.
To prevent this use this line instead:
var numberOne = parseFloat($('#money').val());
Which forces the value to be a (float) number.
You need to declare the function in global scope if you want to use it in inline js
$(document).ready(function() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
})
function depositCal() {
$('.answer').append($('#money').val() + 4);
}
You could also make it a global function by attaching the function to window object.
I think you don't need $(document).ready here and do calculation of finalNumber inside function so that it will give you the correct value of money input, otherwise you will get NaN or empty value-
function depositCal() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
$('.answer').append(finalNumber);
}
You have to keep the depositCal function definition out of $(document).ready(),because first the whole document is loaded,then $(document).ready() is called.So while loading the form,browser finds depositCal as undefined as it is defined after document is fully loaded......So keep the depositCal definition in global scope
Related
I`ve been trying to create a function that (1) uses data input from the HTML to make the calculation and (2) return the result back to the HTML.
I am having some trouble finding the mistake, if you could please help me I'd be glad.
<!DOCTYPE html>
<html>
<body>
<h2>Celcius to Fahrenheit</h2>
<input type="number" id="input-temperature"></input>
<p id="calc-result"></p>
<script>
function toCelsius() {
var x = document.getElementbyId("input-temperature").value;
return (5/9) * (x-32);
}
document.getElementById("calc-result").innerHTML = ("The result is" + toCelsius());
</script>
</body>
</html>
It looks like you made some minor mistakes:
getElementById instead of getElementbyId
You'll need to update the value every time the input field changes: addEventListener('keyup', function() {...})
You have the calculation in reverse: 9 / 5 * x + 32
This is my complete code:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("input-temperature").addEventListener('keyup', onInputChanged);
})
function toCelsius() {
var x = document.getElementById("input-temperature").value;
return 9 / 5 * x + 32;
}
function onInputChanged() {
document.getElementById("calc-result").innerHTML = "The result is " + toCelsius();
}
See this codepen: https://codepen.io/bertyhell/pen/WZQQgZ?editors=1011
You misspelled getElementbyId. It should be getElementById (capital B).
To calculate and display celcius, you can create a button and on click of the button call toCelcius function (as below).
I have made the following changes in the function:
Checking whether the value entered is blank using if (x != "").
function toCelsius() {
var x = document.getElementById("input-temperature").value;
var Celcius = 0;
if ( x != "") Celcius = (5 / 9) * (x - 32);
document.getElementById("calc-result").innerHTML = ("The result is " + Celcius);
}
<input type="number" id="input-temperature"></input>
<p id="calc-result"></p>
<button id="btnCalculate" onclick="toCelsius()">Calculate</button>
I have a counter button which increases the number when clicked.
Also I have an URL like http://localhost:5000/x/.
What I want is:
Printing the counter value at the end of the URL.
For example:
If counter=3, I want to go http://localhost:5000/x/3;
My button type is submit and it increases the value of counter and goes the pagehttp://localhost:5000/x/counter. However, I got 404 Error because the data is on the http://localhost:5000/x/3. Here is the code.
<form action="http://localhost:5000/x/counter">
<script>
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
Thanks.Additional I don't use any framework and I want to handle it just by using JavaScript.
EDIT:
Thanks for your answers. I solved it by using window.location.href function.
Retrieve counter using url of page
var counter = location.href.substring(location.href.lastIndexOf('/')+1);
counter = parseInt(counter);
counter += 1;
Set myform action using counter
document.myform.action = location.href.substring(0,location.href.lastIndexOf('/'))+counter;
Name your form
<form name='myform'>
Please i have a problem here in my work i have an input field and have a button that i use to create new input field with onclick event, but my problem is how to multiply numbers in both input fields and alert the answer.
function create(){
var main_input = document.getElementById("main_input").value,
newinput = document.createElement('input');
newinput.placeholder = "test1";
newinput.value;
document.getElementById("mytest").appendChild(newinput);
}
function multiply(){
var ans = newinput * main_input;
alert(ans);
}
In the absence of clarity, I am posting this solution. Looks like you are not clear on few concepts so let me try to explain them:
You need to move your variables outside the scope of create() so that they are available in the multiply() function.
You cannot just multiply two input fields. You need to take the values from them as shown in the code below.
Hopefully it helps you in moving ahead!
var main_input,newinput;
function create(){
main_input = document.getElementById("main_input");
newinput = document.createElement('INPUT');
newinput.placeholder = "test1";
newinput.value = 10;
document.getElementById("mytest").appendChild(newinput);
}
function multiply(){
var ans = newinput.value * main_input.value;
alert(ans);
}
create();
multiply();
<input id="main_input" value=10 />
<div id="mytest"></div>
Use eval() or you can manually multiply the values like input1.value * input2.value
function create(){
// this is unnecessary, you are creating a new element
// var main_input = document.getElementById("main-input");
var newinput = document.createElement('input');
newinput.placeholder = "test1";
newinput.id = 'test1'; // give the element an id, to access it later by id
// newinput.value; // this too is unnecessary, you'll get the value from the user
if (!document.getElementById('test1')) {
// append the child only if it doesn't exist
document.getElementById("mytest").appendChild(newinput);
}
}
function multiply(){
var newinput = document.getElementById('test1');
var mainInput = document.getElementById("main_input");
alert(eval(newinput.value + '*' + mainInput.value));
// alert(newinput.value * mainInput.value) you can also use this method
}
<div id="mytest">
<input type="text" id="main_input">
</div>
<button onclick="create()">Create</button>
<button onclick="multiply()">Multiply</button>
I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.
This is a the portion I am working on, trying to get button '7' to register so I can do the others.
<div class="container-fluid calc" >
<div class="display">
<label type="text" id="screen">0</label>
<div class="buttons">
<button onClick='calculate()' id='myButton'>7</button>
<button>8</button>
<button>9</button>
Here is the JS I put together
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();
You need to update from
var num = document.getElementById('#myButton').contentValue;
to
var num = document.getElementById('myButton').innerHTML;
You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
Hope this helps!
Update
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
to
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}
Another option is you can is data attribute like this :
<button onClick='calculate()' id='myButton' data-value="7">7</button>
and get it like this :
$("#myButton").attr("data-value");
Hey I'm really new to javascript and i just don't understand why it won't print on my document a number increasing every time i click on my button
<script type="text/javascript">
var x = 0;
function clicker(
y = x+1
)
document.write(y)
return clicker();
</script>
<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
must be :
var x = 0;
function clicker(){
y = x+1;
document.write(y)
}
but, using document.write(y) will erase your button, to remedy this, you can create another element like <div id='status'></div> and use
//use this instead of document.write(y)
var stat = document.getElementById("status");
stat.innerHTML = y;
There are some problems with the script:
The syntax for the function is wrong, so the code won't run at all.
You can't use document.write once the page is loaded, then it will replace the entire page with what you write.
You are calculating a value that is one higher than a value that never changes, so it will only increase the first time, after that it just returns the same result.
Create an element where you can put the result, and increase the variable in the function so that the value changes each time.
<script type="text/javascript">
var x = 0;
function clicker() {
x = x + 1; // or simply x++;
document.getElementById('value').innerHTML = x;
}
</script>
<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
<div id="value"></div>