this is the code i came up with but all it does is this 1+1=11 i need it to do 1+1=2.
<head>
<script type="text/javascript">
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.form1.quantity.value;
two = document.form1.price.value;
c = one + two
document.form1.total.value = (c);
}
function stopCalc(){
clearInterval(interval);
}
</script>
</head>
<body>
<form name="form1">
Quantity: <input name="quantity" id="quantity" size="10">Price: <input name="price" id="price" size="10"><br>
Total: <input name="total" size="10" readonly=true><br>
<input onclick="startCalc();" onmouseout="stopCalc()" type="button" value="Submit">
</form>
</body>
of course this is a really simple form, but you get the idea
please help me tell what i'm doing wrong here
You need to use parseInt() to convert the string to an integer.
c = parseInt(one, 10) + parseInt(two, 10)
use this
c = parseInt(one,10) + parseInt(two, 10);
You need to convert the price values to numeric.
use parseFloat for price since it can have decimal values.
use parseInt with the radix.
e,g:
function calc(){
one = parseInt(document.form1.quantity.value, 10);
two = parseFloat(document.form1.price.value);
c = one + two
document.form1.total.value = (c);
}
You can use the + to convert a string to a number (integer or float)
c = +one + +two;
You can use this
one = document.form1.quantity.value/1;
two = document.form1.price.value/1;
Related
when i'm using the function to add two numbers together it appears next to each other like (2+2=22)
although it works well with other mathematical operators (* and /)
<html>
<head>
<title>Adding</title>
</head>
<body>
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
<script type="text/javascript">
function adding (a, b){
return (a + b);
}
document.getElementById("press").onclick = function(){
var first = document.getElementById("one").value;
var second = document.getElementById("two").value;
alert(adding(first, second));
}
</script>
</body>
You are adding the string "2" plus "2" hence they are just appended. You will need to typecast into a number first.
console.log(parseInt("2")+Number("2"))
The value attribute returns a string, for which the + operator is defined to concatenate. You can use the unary plus operator to simply convert them to a numbers.
function adding(a, b) {
return (a + b);
}
document.getElementById("press").onclick = function() {
var first = +document.getElementById("one").value;
var second = +document.getElementById("two").value;
alert(adding(first, second));
}
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
You can only write parseint where you return.
function adding (a, b){
return (parseInt(a) + parseInt(b));
}
document.getElementById("press").onclick = function(){
var first = document.getElementById("one").value;
var second = document.getElementById("two").value;
alert(adding(first, second));
}
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
I am only beggining my journey with Java Script! I was trying to create an input where I type in a number and after I press a button it would add the value to the var a = 0;
With the script I have written it returns the value as a string. Any ideas on how to make the value of the input be returned as a number? Thanks!!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JAVASCRIPT PRACTISE</title>
</head>
<body>
<div id="payment">
</div>
<button onclick="addToBal(10)" name="button">add 10 bucks</button>
<button onclick="subFromBal(10)" name="button">pay 10 bucks</button><br><br>
<input type="text" id="addInput" value="">
<button type="button" id="addSubmit" onclick="addValue()">add this amount of bucks</button>
<script>
var a = 0;
function addToBal(amtAdded) {
a += amtAdded;
document.getElementById("payment").innerHTML = a;
};
function subFromBal(amtSubstracted) {
a -= amtSubstracted;
document.getElementById("payment").innerHTML = a;
}; //THATS THE END OF THAT SECTION
function addValue(value) {
a += document.getElementById("addInput").value;
document.getElementById("payment").innerHTML = a;
};
</script>
</body>
</html>
Your issue is with:
document.getElementById("addInput").value;
This will return a string, meaning that when you add it, it will concatenate (glue) it to a (as an int+string gives a string), not add which is what you're after.
Thus, you can simply convert this string to a number by putting a + in front of it:
+document.getElementById("addInput").value;
See working example below:
var a = 0;
function addToBal(amtAdded) {
a += amtAdded;
document.getElementById("payment").innerHTML = a;
};
function subFromBal(amtSubstracted) {
a -= amtSubstracted;
document.getElementById("payment").innerHTML = a;
};
function addValue(value) {
a += +document.getElementById("addInput").value; // Add + here to convert string to number (ie: int, float etc)
document.getElementById("payment").innerHTML = a;
};
<div id="payment"></div>
<button onclick="addToBal(10)" name="button">add 10 bucks</button>
<button onclick="subFromBal(10)" name="button">pay 10 bucks</button><br><br>
<input type="text" id="addInput" value="">
<button type="button" id="addSubmit" onclick="addValue()">add this amount of bucks</button>
Input values are of type string. That's why string concatenation is happening. You have to convert the value to number to perform arithmetic operation. You can use Number or prefix the value with + to convert the string value to number:
var a = 0;
function addToBal(amtAdded) {
a += amtAdded;
document.getElementById("payment").innerHTML = a;
};
function subFromBal(amtSubstracted) {
a -= amtSubstracted;
document.getElementById("payment").innerHTML = a;
}; //THATS THE END OF THAT SECTION
function addValue(value) {
a += Number(document.getElementById("addInput").value);
//OR: using +
//a += +document.getElementById("addInput").value;
document.getElementById("payment").innerHTML = a;
};
<div id="payment">
</div>
<button onclick="addToBal(10)" name="button">add 10 bucks</button>
<button onclick="subFromBal(10)" name="button">pay 10 bucks</button><br><br>
<input type="text" id="addInput" value="">
<button type="button" id="addSubmit" onclick="addValue()">add this amount of bucks</button>
You can use Number()
reference
var num = "10";
num = Number(num); // 10 not "10"
you can use parseInt(document.getElementById("addInput").value) which will convert the string as integer.
I thinks you should understand about the string + number in JS.
http://jslearning.info/javascript-numbers/
You can only +/- 2 number, JS will convert to number.
you should not use Number in JS because it cause the speed in JS.
One more thing, if you HTML5, we can use input type is number
<input type="number" name="number">
I need to convert an <input type="date"> value in a timestamp. This is my HTML code:
<input type="date" name="date_end" id="date_end">
This field has a value that I have put like 25/10/2017
My jQuery code is:
var dataEnd = $('[name="date_end"]').val();
if (!dataEnd) {
return false;
} else {
var timestamp_end=$('[name="date_start"]').val().getTime();
console.log("TIMESTAMP END "+timestamp_end);
.....
}
But this is not working... why not?
make a new Date() passing the value of your input as parameter, then call getTime(). here an example:
$('[name="date_end"]').on('change',function() {
var dataEnd = $(this).val();
console.log((new Date(dataEnd)).getTime());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="date_end" id="date_end">
do this
var dateEnd = $('#date_end').val()
var var timestamp_end = Date.parse(date_end)
or
in a single line
var timestamp_end = Date.parse($('#date_end').val())
it works and it's clean
Here is a Solution ( Using pure js ) , I used the unary plus operator operator after converting the value into javascript date object.
function checkDateValue(){
var dateConvertedToTimestamp = (+new Date(document.getElementById('date_value').value));
document.getElementById('date_value_timestamp').innerHTML = dateConvertedToTimestamp ;
}
<input type='date' id='date_value'>
<button onClick='checkDateValue()'> Submit </button>
<div>Timestamp:- <span id='date_value_timestamp'></span></div>
I needed an UNIX timestamp and updated Partha Roy's anwser for my needs.
Javascript :
document.getElementById('dateInput').addEventListener('change', function (){
let inputDate = document.getElementById('dateInput').value ;
let dateConvertedToTimestamp = new Date(inputDate).getTime() ;
console.log(dateConvertedToTimestamp) ;
document.getElementById('resultTime').value = dateConvertedToTimestamp / 1000 ;
}) ;
The /1000 division convert to UNIX timestamp + I track all input change and not only when the form is submited.
HTML :
<input type='date' id='dateInput'>
<input type='hidden' id='resultTime' name='dateTimestamp'>
Don't forget date input are still not well supported, so we can easily adapt this code with classic numbers input.
You can use following code
<script type="text/javascript">
var d = new Date(parseInt($('[name="date_start"]').val()));
var n = d.getTime();
console.log(n);
</script>
I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.