Javascript Multiplication issue in Calculator - javascript

Multiplying 'Area' value with one of three separate fixed values (types of paint:Premium/Luxury/Regular) so as to calculate the total.
There are three values to choose from the dropdown option, but the calculator function always loads the last value as the multiplier.
Calculator works with one fixed value only
window.onload = function(){
function findID(id) { //function to make 'getElementById easier to maintain;
return document.getElementById(id);
}
var calculator = {
multOne: findID('mult-one'),
multTwo: findID('mult-two'),
multThree: findID('mult-three'),
multFour: findID('mult-four'),
product: findID('product'),
calculate: findID('calculate'),
clear: findID('clear')
};
// Onclick Events for buttons
calculator.clear.onclick = function() {
calculator.multOne.value = '';
calculator.multTwo.value = '';
calculator.multThree.value = '';
calculator.multFour.value = '';
calculator.product.value = 'Please Refresh your browser';
console.log(result = 0);
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multTwo.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multThree.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multFour.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
}
<form method="post">
<p class="home-widget-caption" style="color:#ff4102; font-size:14px;">Type of Paint</p>
<select name="types" style="width:120px">
<option id="mult-two" value="30">Luxury</option>
<option id="mult-three" value="20">Premium</option>
<option id="mult-four" value="10">Regular</option>
</select>
<br>
<p class="home-widget-caption" style="color:#ff4102; font-size:14px; margin-top:10px;">Painting Area</p>
<input type="text" id="mult-one" style="width:120px"> <span style="color:#999999">sq.ft.</span>
<br><br>
<div style="text-align:center">
<button type="button" id="calculate" style="padding:10px 30px 10px 30px; margin-bottom:15px">Calculate My painting cost</button>
<button type="button" id="clear" style="display:none">Clear</button>
</div>
<p class="home-widget-caption" style="color:#ff4102; font-size:16px">Your total expenditure</p>
<input type="text" id="product" style="width:270px">
<br><br>
</form>

You are not supposed to have multiple
calculator.calculate.onclick = function() {}
You must have only one, where you get the selected value of your <select>, and do the calculations.
Your <select> could have an id you would use later to get selected option value :
<select id="typesID" name="types" style="width:120px">
<option id="mult-two" value="30">Luxury</option>
<option id="mult-three" value="20">Premium</option>
<option id="mult-four" value="10">Regular</option>
</select>
Then in your JS side :
calculator.calculate.onclick = function() {
var e = document.getElementById("typesID");
var selectedValue = e.options[e.selectedIndex].value;
var result = calculator.multOne.value * selectedValue;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}

Related

How to make auto calculate in dynamic multiple form?

function sum()
{
$(document).on('keyup', "*[data-field='unit'],*[data-field='unit_price']", function(e)
{
var unit = document.getElementById('unit').value;
var unitPrice = document.getElementById('unit_price').value;
var result = parseInt(unit) * parseInt(unitPrice);
if (!isNaN(result))
{
document.getElementById('amount').value = result;
}
});
}
p/s: this only function at normal form. but not dynamic form.
[edit ?]
$('#unit, #price').on('input',function()
{
let qty = parseInt($('#unit').val())
, price = parseFloat($('#price').val())
;
$('#amount').val((qty * price ? qty * price : 0).toFixed(2));
});
you can do this whit jQuery Plugin i write simple one
you can test it on this :
$.fn.sum = function(options) {
"use strict";
var self = this;
self.defaults = {
unit : '[data-field="unit"]',
unit_price : '[data-field="unit_price"]',
result : '[data-field="amount"]',
onCalculate : function(result){},
};
self.settings = $.extend({},self.defaults, options );
var unit_count = $(self).find('input'+self.settings.unit).length;
var unit_price_count = $(self).find('input'+self.settings.unit_price).length;
if(unit_count > 0 && unit_price_count > 0){
var unit, unit_price=0, result=0;
$($(self).find('input'+self.settings.unit_price)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
$($(self).find('input'+self.settings.unit)).bind('keyup', function(){
unit = $(this).closest('form').find('input'+self.settings.unit).val();
unit_price = $(this).closest('form').find('input'+self.settings.unit_price).val();
result = sum(unit, unit_price);
self.settings.onCalculate(self, $(this), result);
});
function sum(unit, unit_price){
var result = parseInt(unit) * parseInt(unit_price);
if (!isNaN(result)) {
return result;
}
}
}
}
$(document).ready(function(){
$('form').sum({
onCalculate: function(self, active, result){
$(active).closest('form').find(self.settings.result).val(result);
},
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="fff33">
<legend>
two
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit22">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price22">
<input type="text" data-field="amount" disabled>
</form>
<br>
<br><br>
<form id="fff">
<legend>
one
</legend>
<lable>unit</lable>
<input type="text" data-field='unit' id="unit">
<br>
<lable>unit_price</lable>
<input type="text" data-field='unit_price' id="unit_price">
<input type="text" data-field="amount" disabled>
</form>
<br><br>

How can I calculate the total value of amount due after choosing different option from drop-down list?

I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.

Validation with jquery and datalist

I have an similar problem like this post: Validation with datalist
However the answer of FelDev is in JavaScript I need it in jquery .
I am new to jquery therefore it would be of great help if some can help.
In the following the answer of FelDev:
let btn = document.getElementById("btnSend");
let form = document.getElementById("zeForm");
let input = document.getElementById("zeInput");
let msg = document.getElementById("msg");
let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist
btn.onclick = function() {
let allGood = false;
allowedValues.forEach(function(elm) {
if(elm === input.value) {
allGood = true;
return;
}
})
if(allGood) {
msg.innerHTML = "Success!!";
msg.style.color = "green";
//form.submit();
} else {
msg.innerHTML = "This value is not accepted";
msg.style.color = "red";
}
msg.style.display = "inline";
}
#msg {
display: none;
}
#btnSend {
display: block;
margin-top:1rem;
}
<form id="zeForm">
<input id="zeInput" type="text" list="typ" name="name" placeholder="gtown" >
<datalist id="typ">
<!-- notice the absence of a <select> here... -->
<option value="atown">atown</option>
<option value="btown">btown</option>
<option value="ctown">ctown</option>
</datalist>
</input>
<p id="msg"></p>
<button id="btnSend" type="button">send</button>
</form>
So do you need a translation?
So the jquery of this js is :
let btn = $("#btnSend");
let form = $("#zeForm");
let input = $("#zeInput");
let msg = $("#msg");
let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist
btn.on('click' , function() {
let allGood = false;
allowedValues.each(function(index, element) {
if (element === input.value) {
allGood = true;
return;
}
})
if (allGood) {
msg.text("Success!!");
msg.attr('style',"color:green");
//form.submit();
} else {
msg.text("This value is not accepted";
msg.attr('style',"color:red");
}
msg.attr('style',"display:inline");
});

Converthing Celcius/Fahrenheit with Select Menu

I want to convert, with Select menu. So the first input box will read what temperature to convert from Select Menu, But it didn't work. When I select menu Celsius so the input will read the temperature as Celsius.
function myFunction() {
if (document.getElementById("temperature").value == "Celcius") {
convertc();
} else {
convertf();
}
}
function convertc() {
var x;
document.getElementById("demo").innerHTML = " Degree Celcius ";
x = (document.getElementById("c").value - 32) * 5 / 9;
document.getElementById("f").value = Math.round(x);
}
function convertf() {
var x;
document.getElementById("demo").innerHTML = " Degree Fahrenheit ";
x = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(x);
}
<h2>JavaScript Celcius to Fahrenhet</h2>
<form>
<select id="temperature" onchange="myFunction()">
<option value="Celcius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="c"><span id="demo"> Degree </span></p>
<p>
<input id="f"></p>
You have multiple selector wrong in your Html as it has spaces on the ID's and in JavaScript selector you don't have space.
Just fix spaces in your elements ID's and it will work
e.g. "demo " != "demo"
Below is corrected ID's and JavaScript Selectors
function myFunction() {
if (document.getElementById("temperature").value == "Celcius") {
convertc();
} else {
convertf();
}
}
function convertc() {
var x;
document.getElementById("demo").innerHTML = " Degree Celcius ";
x = (document.getElementById("c").value - 32) * 5 / 9;
document.getElementById("f").value = Math.round(x);
}
function convertf() {
var x;
document.getElementById("demo").innerHTML = " Degree Fahrenheit ";
x = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(x);
}
<body>
<h2>JavaScript Celcius to Fahrenhet</h2>
<form>
<select id="temperature" onchange="myFunction()">
<option value="Celcius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="c"><span id="demo"> Degree </span></p>
<p>
<input id="f" ></p>
</body>
If you want to automatically select the first select option, you will need to trigger the event.
Note: For the trigger functionality, I reused logic from a previous answer of mine.
I also converted the calculations to lambda constants for brevity, see below.
const FAHRENHEIT_TO_CELSIUS = (value) => (value - 32) * 5 / 9;
const CELSIUS_TO_FAHRENHEIT = (value) => value * 9 / 5 + 32;
// ==============================================================
var comboEl = document.getElementById('temperature');
addEventListener(comboEl, 'change', onComboChange); // Add an event listener.
triggerEvent(comboEl, 'change', {}); // Automatically trigger the event.
// ==============================================================
function onComboChange(e) {
var inputValue = document.getElementById('input-degrees').value;
if (e.target.value === 'Celsius') {
updateDisplay('Celsius', CELSIUS_TO_FAHRENHEIT(inputValue));
} else {
updateDisplay('Fahrenheit', FAHRENHEIT_TO_CELSIUS(inputValue));
}
}
function updateDisplay(label, value) {
document.getElementById('degrees-label').innerHTML = 'Degrees ' + label;
document.getElementById('output-degrees').value = Math.round(value);
}
// ==============================================================
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function() {
handler.call(el);
});
}
}
function triggerEvent(el, eventName, options) {
var event;
if (window.CustomEvent) {
event = new CustomEvent(eventName, options);
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, true, true, options);
}
el.dispatchEvent(event);
}
<h2>JavaScript Celsius to Fahrenheit</h2>
<form>
<select id="temperature">
<option value="Celsius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="input-degrees" value="0" />
<span id="degrees-label">Degrees</span>
</p>
<p><input id="output-degrees" /></p>

How will i prevent duplication of value and empty value

How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}

Categories