javascript to calculate simple multiplication automatically upon changing any number [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm not a javascript programmer, but I have to use it for a calculation I need to do on a wordpress page.
Here is what I need:
3 fields in html where I can enter a number (a form).
a text field where the multiplication is "printed"
if I change one element, a new result must apear, without me needing to push any button.
any idea on how to do this?
I know how to do the calculation as such, but not that it works automatically.
HEre is what I got so far:
<html>
<head>
<title>Simple Javascript Calculator - Basic Arithmetic Operations</title>
<script language="javascript" type="text/javascript">
function multiply(){
a=Number(document.calculator.number1.value);
b=Number(document.calculator.number2.value);
c=a*b;
document.calculator.total.value=c;
}
</script>
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- Here user will enter 1st number. -->
Number 1: <input type="text" name="number1">
<!-- Here user will enter 2nd number. -->
Number 2: <input type="text" name="number2">
<!-- Here result will be displayed. -->
Get Result: <input type="text" name="total">
<!-- Here respective button when clicked, calls only respective artimetic function. -->
<<input type="button" value="MUL" onclick="javascript:multiply();">
</form>
</body>
</html>
thanks

jsFiddle Demo
You are going to be forced to use an interval if you want to monitor two inputs and handle all changes (such as pasting in, either from a mouse, from ctrl+v, from using the edit+paste browser input, from typing, etc.).
If you do not need to handle all cases, then onkeyup will work as Bart suggests. Here is an interval approach:
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
d.innerHTML = x.value * y.value;
}
x.onblur = calculate;
calculate();

This will not answer the problem for your specific question but a nice way to do your calculations is through the eval function.
http://jsfiddle.net/gL3YF/1/
The HTML:
<input type="text" id="expression" value="1 + 1" />
<hr />
<h3 id="result"></h3>
The Javascript:
var input = document.getElementById('expression');
input.onkeyup = function () {
var result = document.getElementById('result');
result.innerHTML = eval(this.value);
};
//evaluate initial value
input.onkeyup();

use the onchange event on each input element so that when a user changes input[value] an operation is triggered. You should also cache the previously performed operation so that it's applied to the operands when onchange event is triggered

Related

Accessing and manipulating HTML input using JavaScript

I'm an new amateur programmer that is having trouble using HTML and JavaScript together. We were tasked to make a simple program that asks us what's the maximum number, I made the logic but still having trouble with this case.
Currently this is the progress with my code
var num1;
var num2;
var num3;
var max;
if (num1 < num2) {
if (num2 < num3) {
num3 = max;
} else if (num2 > num3) {
num2 = max;
}
} else if (num1 > num2) {
if (num1 > num3) {
num1 = max;
} else if (num1 < num2) {
num2 = max;
}
}
alert("The maximum number is: " + max);
<h1>Laboratory 06</h1>
<p>2. Write a JavaScript program to determine the maximum number using 3 input box.</p>
<blockquote>
<label for=num1>First number:</label><br>
<input type="text" id="a" name=num1><br><br>
<label for=num2>Second number:</label><br>
<input type="text" id="b" name=num2><br><br>
<label for=num3>Third number:</label><br>
<input type="text" id="c" name=num3><br><br>
<button type="button">Enter</button>
</blockquote>
The main problem with your code is that it runs straight away, long before a user has entered any number. The next problem with it is that you never read the values from the inputs.
What you instead want is for the code to wait until an event occurs - which, in your case is the event, that the user clicks the Enter button.
For reacting to user actions (and more), Javascript has the concept of eventListeners, which you can add to any element. There is many different types of events; the one you care about here is the click event.
To add it to the button, you first need your Javascript to learn where your button element is. To find it in the page, Javascript offers the document.querySelector() method.
Once you have found it, you can call the addEventListener() method on the element (all HTML elements have this method built-in).
For an explanation of the rest, check the source code comments (lines that begin with //):
// first we need to find the button in the page,
// so we can access it in our Javascript
// the following finds the first <button> element in the page.
const button = document.querySelector('button');
// every HTML element has a addEventListener method
// that takes two arguments:
// the first is the name of the event you want to listen to (String),
// the second is a function that will be executed every time
// the event occurs.
button.addEventListener('click', function() {
// when the user clicks the button, we read what is in the inputs.
// to do that, we first need our JS to find the inputs.
// in this case this is especially easy because each of them has a
// unique identifier (id), so we can use
// document.getElementById(id)
// to find it.
// Once found, we immediately read the value from the input.
let aValue = document.getElementById('a').value;
let bValue = document.getElementById('b').value;
let cValue = document.getElementById('c').value;
// because the value of any input element is always a String,
// we now convert it to a Number.
aValue = parseFloat(aValue);
bValue = parseFloat(bValue);
cValue = parseFloat(cValue);
// now we use another built-in object, Math, and on it, the
// Math.max function, to find the largest number.
const maxValue = Math.max(aValue, bValue, cValue);
// to output the maxValue, we use console.log rather than
// alert. To see the output in the browser, open the browser's
// developer tools (F12 on Windows), and click the "Console" tab.
// To make sure not to output anything if no number was entered
// before the button was clicked, we check if maxValue is a proper
// number. Javascript has the NaN datatype (Not a Number),
// and you can check for it using isNaN(variable)
if (!isNaN(maxValue)) { // if maxValue is not "Not a number"
console.log("The maximum number is: " + maxValue);
}
})
<h1>Laboratory 06</h1>
<p>2. Write a JavaScript program to determine the maximum number using 3 input box.</p>
<blockquote>
<label for=num1>First number:</label><br>
<input type="text" id="a" name=num1><br><br>
<label for=num2>Second number:</label><br>
<input type="text" id="b" name=num2><br><br>
<label for=num3>Third number:</label><br>
<input type="text" id="c" name=num3><br><br>
<button type="button">Enter</button>
</blockquote>

Divide a span value by a static number - JS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a field in a table which takes in a value from an input field
<td>€<span class="totalNumber"></span></td>
I have another field that has a static number so example 50%.
The result I want is the third field to have totalNumber divided by .50 so my final field be my result.
Example:
totalNumber takes in the value 100.
Second field is static 50%
So my result field will be 50
I've tried using: var value = Math.floor(#totalNumber * .50);
I'm not sure if that could be used or my syntax is just wrong.
You will need simple javascript.
var num = parseInt($('span.totalNumber').text());
var staticnum = parseInt($('span.staticNumber').text());
var answer = (num * staticnum)/100;
$('span.result').text(answer);
var num = parseInt($('span.totalNumber').text());
var staticnum = parseInt($('span.staticNumber').text());
var answer = (num * staticnum)/100;
$('span.result').text(answer);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Total Number : <span class="totalNumber">200</span>
</div>
<div>
Static Number : <span class="staticNumber">50%</span>
</div>
<div>
Result : <span class="result"></span>
</div>
Your provided code is to meager to provide a good answer but here is an example how you can do something like that.
At total you enter the number you want to divide.
At percent you add the percentage.
Both these inputs have a change event bound to them with the same handler so that if any of these changes it executes the handler. You probably want to check too if not both inputs are empty.
var total = document.getElementById('totalValue').addEventListener('change', calculate);
var percent = document.getElementById('percentValue').addEventListener('change', calculate);
function calculate() {
var total = document.getElementById('totalValue');
var percent = document.getElementById('percentValue');
var calc = document.getElementById('calculatedValue');
calc.value = total.value * (percent.value / 100)
}
<label for="totalValue">Total</label>
<input id="totalValue" type=text />
<br />
<label for="percentValue">Percent</label>
<input id="percentValue" type=text />
<br />
<label for="calculatedValue">Calculated</label>
<input id="calculatedValue" type=text />

Strange jquery bug in simple code

I have a simple html code with form:
<span class="price"></span>
Enter amount:
<input type="text" class="form-control amount" name="amount" value="500">
<!--Next input fields are hidden by Bootstrap class "hide"-->
<input type="text" name="minimal-amount" class="hide minimal-amount" value="500">
<input type="text" name="oneprice" class="hide oneprice" value="0.20">
<script>
$(".amount").on("change", function(){
var am = $(".amount").val();
var min = $(".minimal-amount").val()
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
</script>
Idea of this code is very simple. When user put in amount field digits, my script should check, if that, what user put is smaller than minimum available value in minimal-amount field, script changes value of amount field to default minimal-amount.
But the problem is, that id I just add 0 in amount field (and it's value become 5000) everything is ok, but when I changes value of amount field to 1000, script changes value of amount field to default, as if it smaller them minimul-amount.
What I do wrong, and how can I fix this problem?
P.S. Example of this code you can find here - http://friendfi.me/tests/amount.php
You should parse the value before use. Because .val() will return only string type.
$(".amount").on("change", function(){
var am = parseFloat($(".amount").val());
var min = parseFloat($(".minimal-amount").val());
if(am<min){
$(".amount").val($(".minimal-amount").val());
}else{
var am = $(".amount").val();
var oneP = $(".oneprice").val();
var finalPrice = am*oneP;
$(".price").html(finalPrice);
}
});
There are a lot of gotchas in that code. Here is a working JSBin: http://jsbin.com/qilob/2/edit?html,js,output
Highlights
You need the DOM to be initialized before you can work with it.
Wrapping this in a function passed to jQuery will make it wait till
the page finishes loading before manipulating it.
$(function() { ... });
Use cached values since the elements are not going to change much.
This saves the need to parse the selectors multiple times. It also saves
on typing and readability.
var $amount = $("#amount");
var $minimalAmount = $("#minimal-amount");
var $onePrice = $("#oneprice");
var $finalPrice = $("#price");
When parsing a string to an Int you need to use parseInt
var amount = parseInt($amount.val(), 10);
Conversely when parsing a string to a Float you need to use parseFloat
var price = parseFloat($onePrice.val());
JavaScript can not handle float based arithmetic well.
rounding errors are bad especially when dealing with money we need
to move the decimal place to prevent rounding errors in the more significant
parts of the price value.
var total = (amount * (price * 100)) / 100;
See it in action in the JSBin.

Explanation needed regarding JavaScript arrays and how they are being implemented [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have some JavaScript written by someone else and I'm trying to figure our exactly where some values are coming from, how they are formatted and what is being done with them. The values in question are citNumFirst, dateFirst, cdValues and cnValues.
This JavaScript is used to recursively open form fields for numbers and dates, then make an Ajax request (I think), but the Ajax data doesn't make any sense (value is: data: "countCitNum=" + countCitNum,)
Here is the code I need help with. Again, I'm trying to figure out where these values citNumFirst, dateFirst, cdValues and cnValues are coming from as these are what are being sent through the form submission (according to Fiddler).
My thinking is that this can all be done more efficiently with PHP, but I'm curious if the Ajax is even doing anything here, and if not are the values "cdValues" and "cnValues" being send as Javascript Arrays, or objects using the input forms.
$(document).ready(function() {
var citArray = [];
var thisCount = 1;
varcountCitNum = -1;
var cnArray = [];
var citNum = '';
var cnFirst = '';
var cdArray = [];
var issueDate = '';
$("#cnValues").val(cnArray);
$("#cdValues").val(cdArray);
function addCitNumber(){
var citNumField = document.getElementById("citNumFirst");
if(citNumField.value ==''){
var addfield_msg = "<span style='color:#F00;'>Please enter <br />Citation Number</span>";
$('#addfield_error').removeClass('hideCat');
$('#addfield_error').append(addfield_msg);
return false;
}else{
countCitNum++;
var addHTML = '';
var addDateHTML = ''
$.ajax({
type: "POST",
url: "/ci/ajaxCustom/addCitNum",
data: "countCitNum=" + countCitNum,
success: function(results){
if(results){
countCitNum = results;
}
addHTML = '<div id="newCitNum_'+countCitNum+'"><br /><strong>Citation Number:</strong><br /><input type="text" id="citNumInput_'+countCitNum+'" onchange="setCitNum(this,'+countCitNum+')"/></div>';
addDateHTML = '<div id="newDate_'+countCitNum+'"><br /><strong>Citation Issue Date:</strong><br /><input type="text" id="citDateInput_'+countCitNum+'" class="date" onchange="setIssueDate(this,'+countCitNum+')" readonly="readonly"/><img src="/euf/assets/themes/standard/images/delete_x.gif" width="29" height="23" border="0" class="imgDelete"/>Delete Citation Number</div>';
$('#anotherCitNum').append(addHTML);
$('#anotherCitDate').append(addDateHTML);
document.getElementById("#citDateInput_"+countCitNum);
$("#citDateInput_"+countCitNum).attr("disabled",true);
$(".date").datepicker();
}
});
}
data="";
}
*//******
Set Additional Citation Numbers and enable the date input
******/
function setCitNum(obj, countCitNum){
if(obj.value !='')
{
cnArray[countCitNum] = obj.value;
$("#cnValues").val(cnArray);
$("#citDateInput_"+countCitNum).removeAttr("disabled");
}else{
$('#citDateInput_'+countCitNum).val('');
$("#citDateInput_"+countCitNum).attr("disabled", true);
}
}
/******
Set Issue Date of additonal citations
******/
function setIssueDate(obj, countCitNum){
if(obj.value !=''){
cdArray[countCitNum] = obj.value;
}else{
cdArray[countCitNum] = '';
}
$("#cdValues").val(cdArray);
}
/******
Set Citation Number and enable date input unless Citation Number is blank
******/
function setFirstNum(obj){
cnFirst = obj.value;
$('#addLink').empty();
if(obj.value !='')
{
$("#citNumFirst").val(cnFirst);
$("#dateFirst").removeAttr("disabled");
$('#addfield_error').empty();
$('#addfield_error').addClass('hideCat');
var addLinkHTML = "<a href='javascript:void(0)' onclick='addCitNumber();'>Click here to add another Citation Number</a>"
$('#addLink').append(addLinkHTML);
}else{
$('#dateFirst').val('');
$("#dateFirst").attr("disabled", true);
}
}
/******
Set Issue Date of citation
******/
function setFirstDate(obj){
var issueDate = obj.value;
$("#dateFirst").val(issueDate);
}
Here is the associated HTML
<input type="hidden" name="cnValues" id="cnValues" />
<input type="hidden" name="cdValues" id="cdValues" />
<input type="text" id="citNumFirst" onblur="setFirstNum(this)" value=""/></div>
<div id="addfield_error" class="hideCat"></div>
</div>
<div id="anotherCitDate" style="float:left; padding-left:15px">
<input type="text" id="dateFirst" class="date" onchange="setFirstDate(this)" value="" readonly="readonly"/>
As far as I can tell, this is what's happening:
citNumFirst and dateFirst are the initial inputs. When citNumFirst input is changed (note: this definitely needs input validation), "Click here to add another" link appears. Clicking it will increment countCitNum, send that to the Ajax call, and if it's successful, display an additional set of date/number inputs which can be used to create a new citation number.
Ajax call: I'm not entirely sure what's going on here because what it's passing is the index of the input fields (countCitNum) that will be added (starting with zero and not counting the initial set). It's not passing the actual number or date, and it looks like it's expecting to receive that same index as results.
cnValues and cdValues store cnArray and cdArray, which are used to store the numbers and dates, respectively, of citations added using these newly created input fields. cnArray[0] corresponds to the value in input #newCitNum_0; cdArray[0] corresponds to #newDate_[0]. Any updates made to these input fields result in changes to the array, but I'm not seeing them being used anywhere in your code snippet (but since they are hidden inputs, they are probably being used after form submit).

Simple JavaScript captcha using random array [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I have created a simple Javascript Captcha but currently the values are randomly generated but I want to get values from the array only(want to randomized these two array), plz check my code I want to do this using simple Javascript with no dependency also plz fix the function validate().
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function myCaptcha() {
var leftnum =[5, 10, 15, 20];
var rightnum =[2, 4, 6, 8];
var leftnum = Math.floor(Math.random()*11);
var rightnum = Math.floor(Math.random()*11);
var tolnum = leftnum + rightnum ;
document.getElementById("sh").innerHTML = leftnum + " + " + rightnum;
}
function validate() {
var captchanow = document.getElementById("captcha");
if (captchanow != "") {
alert("Please enter a captcha");
return false;
}
else if(captchanow == tolnum) {
alert("wrong captcha entered");
return false;
}
else {
form.submit
}
return true;
}
</script>
</head>
<body onload="myCaptcha()">
<form action="" method="post" onsubmit="return false;">
<p>Captcha :
<input name="captcha" type="text" id="captcha" value="" />
<label id="sh" value=""></label></p>
<p>
<input type="submit" name="button" id="button" value="Submit" onclick="validate()"/>
</p>
</form>
</body>
</html>
I discourage you strongly from using a JavaScript captcha as it will entirely remove the point of a captcha, which is to not be machine-readable.
Instead, I would recommend you to switch to something like reCAPTCHA.
Using a JavaScript CAPTCHA will only upset your users and spambots may solve it with their eyes closed [figuratively].
First of all, a Javascript CAPTCHA is completely pointless, as the bots that you want to stop won't be running the Javascript in the page.
Anyhow, this is how you pick items from arrays:
var leftnums =[5, 10, 15, 20];
var rightnums =[2, 4, 6, 8];
var leftnum = leftnums[Math.floor(Math.random() * leftnums.length)];
var rightnum = rightnums[Math.floor(Math.random() * rightnums.length)];
To get the value of the input field, use the value property:
var captchanow = document.getElementById("captcha").value;
To check if two numbers differ, use the != operator, and parse the string to an integer value:
else if(parseInt(captchanow,10) != tolnum) {

Categories