Product configurator doesn't work -.- - javascript

I built a WooCommerce configurator on my landingpage, but unfortuantely it doesn't work. Console shows problem with JS code because of .hasclass() which I just don't get - can anyone help me?
Thanks a lot!
HTML:
<div id="amounts">
<button type="button" class="amount-button dreiriegel" value="6,50€" name="7,47€">
<h2>3 Natural Energy-Riegel</h2>
</button>
<button type="button" class="amount-button zwoelfriegel" id="selected" value="23,88€" name="29,88">
<h2>12 Natural Energy-Riegel</h2>
<span>Du sparst xyz</span>
</button>
<button type="button" class="amount-button vierundzwanzigriegel" value="44,90€" name="59,76€">
<h2>24 Natural Energy-Riegel</h2>
<span>Du sparst yz</span>
</button>
</div>
<div id="offer-price"></div>
<div id="normal-price"></div>
<div id="input_div">
<input type="button" value="-" id="moins" onclick="minus()">
<div value="1" id="count">1</div>
<input type="button" value="+" id="plus" onclick="plus()">
</div>
<form id=“bestell-button" action="/cart/?add-to-cart=294&variation_id=299&quantity=1&attribute_pa_variante=12-riegel" method="POST">
<input type="submit" value="Jetzt bestellen">
</form>
CSS:
#selected {
background-color: green;
}
.amount-button {
width: 100%;
}
.amount-button:hover {
cursor: pointer;
}
.amount-button:hover {
background: #DDD;
}
JavaScript:
jQuery(document).ready(function () {
var selected_oprice = jQuery('#selected').val();
jQuery('#offer-price').html(selected_oprice);
var selected_nprice = jQuery('#selected').attr("name");
jQuery('#normal-price').html(selected_nprice);
});
jQuery(function($) {
$('.amount-button').click(function() {
$('.amount-button').not(this).removeAttr('id', 'selected');
$(this).attr('id', 'selected');
var selected_oprice = jQuery('#selected').val();
jQuery('#offer-price').html(selected_oprice);
var selected_nprice = jQuery('#selected').attr("name");
jQuery('#normal-price').html(selected_nprice);
});
});
var count = 1;
var countEl = document.getElementById("count");
function plus(){
count++;
countEl.value = count;
countEl.innerHTML = count;
}
function minus(){
if (count > 1) {
count--;
countEl.value = count;
countEl.innerHTML = count;
}
}
function getVariation(){
var dieses=jQuery(this);
if (dieses.hasClass("dreiriegel")) {
return 297;
}
else if (dieses.hasClass("zwoelfriegel")) {
return 299;
}
else if (dieses.hasClass("vierundzwanzigriegel")) {
return 300;
}
}
function getAttribute(){
var jenes=jQuery(this);
if (jenes.hasClass("dreiriegel")) {
return 3-riegel;
}
else if (jenes.hasClass("zwoelfriegel")) {
return 12-riegel;
}
else if (jenes.hasClass("vierundzwanzigriegel")) {
return 24-riegel;
}
}
function getLink(){
var href=window.location;
var amount=document.getElementById("#count").value;
var attribute=jQuery("#selected").getVariation();
var variante=jQuery("#selected").getAttribute();
href=href+"cart/?add-to-cart=294&variation_id="+variante+"&quantity="+amount+"&attribute_pa_variante="+attribute;
return href;
}

Related

Javascript - Stuck in an if statement - Beginner Question

I am trying to make a calculator, simply my problem is this:
Page refreshes.
User clicks on any number and the number gets added to the First Number: nums_clicked h1.
If user clicks on an operator sign(+ - *), the clicked boolean becomes true.
If clicked is true, add the numbers clicked to the Second Number: nums_clicked
My problem is even if I click on an operator sign, it keeps adding the numbers I am clicking to the First Number: nums_clicked h1, why is that happening? It even happens while clicked is TRUE!
My
let numbers = [];
let first_num = "";
let second_num = "";
let clicked = false;
let result = false;
for (var i = 0; i < 9; i++) {
numbers[i] = parseInt(document.querySelectorAll("button")[i].innerText);
}
for (var i = 9; i < 12; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
clicked = true;
});
}
if (!clicked && !result) {
for (let i = 0; i < 9; i++) {
if (clicked) {
break;
}
document.querySelectorAll("button")[i].addEventListener("click",
function() {
console.log("clicked = " + clicked);
first_num += this.innerText;
document.getElementById("firstNumber").innerText = "Number1: " + first_num;
});
}
}
if (clicked && !result) {
for (let i = 0; i < 9; i++) {
document.querySelectorAll("button")[i].addEventListener("click",
function() {
second_num += this.innerText;
document.getElementById("secondNumber").innerText = "Number2: " + second_num;
});
}
}
document.getElementById("result-btn").addEventListener("click",
function() {
result = true;
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
<title></title>
</head>
<body>
<div class="container">
<button type="button" name="button">1</button>
<button type="button" name="button">2</button>
<button type="button" name="button">3</button>
<br>
<button type="button" name="button">4</button>
<button type="button" name="button">5</button>
<button type="button" name="button">6</button>
<br>
<button type="button" name="button">7</button>
<button type="button" name="button">8</button>
<button type="button" name="button">9</button>
<br>
<br>
<button type="button" name="button">+</button>
<button type="button" name="button">*</button>
<button type="button" name="button">-</button>
<br>
<button id="result-btn" type="button" name="button">Result</button>
<h1 id="firstNumber">First Number: </h1>
<h1 id="secondNumber">Second Number: </h1>
<h1 id="result">Result: </h1>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Code:
Screenshot of index.html (Red part while clicked=false and blue part is while clicked=true:
Your main issue was that you were never creating the click events for the second number, because those were behind the if(!result.... Like Barmar mentioned, even if you created the click events for the second number, the events from the first number would be triggered also and it would still not work. Also you did not had anything for setting the actual results.
I made some changes on your code to make it simpler to understand, but still trying to follow your logic. Here you go:
let first_num;
let second_num;
let operation;
for (var i = 9; i < 12; i++) {
document.querySelectorAll('button')[i].addEventListener('click', function () {
operation = this.innerText;
});
}
for (let i = 0; i < 9; i++) {
document.querySelectorAll('button')[i].addEventListener('click', function () {
if (!operation) {
document.getElementById('firstNumber').innerText += this.innerText;
} else {
document.getElementById('secondNumber').innerText += this.innerText;
}
});
}
document.getElementById('result-btn').addEventListener('click', function () {
first_num = document.getElementById('firstNumber').innerText;
second_num = document.getElementById('secondNumber').innerText;
document.getElementById('result').innerText = calculate(
parseInt(first_num),
parseInt(second_num),
operation
);
});
function calculate(a, b, operation) {
if (operation === '+') {
return sum(a, b);
} else if (operation === '-') {
return minus(a, b);
} else if (operation === '*') {
return multiply(a, b);
}
}
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
<div class="container">
<button type="button" name="button">1</button>
<button type="button" name="button">2</button>
<button type="button" name="button">3</button>
<br />
<button type="button" name="button">4</button>
<button type="button" name="button">5</button>
<button type="button" name="button">6</button>
<br />
<button type="button" name="button">7</button>
<button type="button" name="button">8</button>
<button type="button" name="button">9</button>
<br />
<br />
<button type="button" name="button">+</button>
<button type="button" name="button">*</button>
<button type="button" name="button">-</button>
<br />
<button id="result-btn" type="button" name="button">Result</button>
<h1>First Number: <span id="firstNumber"></span></h1>
<h1>Second Number: <span id="secondNumber"></span></h1>
<h1>Result: <span id="result"></span></h1>
</div>

To find if a button is selected

Ive got HTML code with a button group and a submit button. The script code checks if it is selected or not and submits based on that selection. If none of the buttons are selected, then display the alert.
$("#Save").on("click", Save);
function Save(e) {
if (GeneralStatusAlert(e) == false) {
return;
} else {
$('#frmSubmit').submit();
}
}
function GetGeneralStatus() {
var value = "";
var row = $("#btnGeneral").closest(".row")
var object = $(this).find(".btn-group");
value = $(object).find(".selected");
return value;
}
function GeneralStatusAlert(e) {
var value = GetGeneralStatus();
if (value.length < 1) {
alert("Please set Status.");
return false;
}
return true;
}
$('.testRow button').click(function () {
$(this).addClass("selected");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row testRow">
<div class="btn-group btnGeneral">
<button type="button" class="btn btn-success btnStatus" value="Open">Open</button>
<button type="button" class="btn btn-danger btnStatus" value="Closed">Closed</button>
</div>
</div>
<br/>
<br/>
<div class="row">
<button id="Save" class="btn btn-primary"><i class="fa fa-share-square-o"></i> Save</button>
</div>
It does not work. What am I missing?
EDIT : Added the select button class on button click.
I've updated your JS a little:
$("#Save").on("click", Save);
$(".btnStatus").on("click", function(){
$(".btnStatus").removeClass("selected");
$(this).addClass("selected");
});
function Save(e)
{
if (GeneralStatusAlert(e) == false) {
return;
}
else{
$('#frmSubmit').submit();
}
}
function GetGeneralStatus() {
var value = "";
value = $("div.btn-group").find(".selected");
return value;
}
function GeneralStatusAlert(e) {
var value = GetGeneralStatus();
if (value.length < 1) {
alert("Please set Status.");
return false;
}
return true;
}
Basically you weren't adding the selected class when clicking your status buttons. Also your code var object = $(this).find(".btn-group"); wasn't finding anything. (Due to using this)
There are few issues in your sample code
1: bootstrap.js is dependent on JQuery, so need to add that first.
2: Missing code to add selected class on status button
3: There is no element with id btnGeneral, you are using wrong selector. btnGeneral is a class and should be accessed by .
4: You may meant $(row) instead of $(this)
var row = $("#btnGeneral").closest(".row")
var object = $(this).find(".btn-group");
Updated sample code.
$("#Save").on("click", Save);
$(".btn").on("click", function(){
$(this).addClass("selected");
$(this).siblings().removeClass("selected");
});
function Save(e) {
if (GeneralStatusAlert(e) == false) {
return;
} else {
alert("Submitting");
$('#frmSubmit').submit();
}
}
function GetGeneralStatus() {
var value = "";
var row = $(".btnGeneral").closest(".row")
var object = $(row).find(".btn-group");
value = $(object).find(".selected");
return value;
}
function GeneralStatusAlert(e) {
var value = GetGeneralStatus();
if (value.length < 1) {
alert("Please set Status.");
return false;
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.css" rel="stylesheet"/>
<div class="row">
<div class="btn-group btnGeneral">
<button type="button" class="btn btn-success btnStatus" value="Open">Open</button>
<button type="button" class="btn btn-danger btnStatus" value="Closed">Closed</button>
</div>
</div>
<br/>
<br/>
<div class="row">
<button id="Save" class="btn btn-primary"><i class="fa fa-share-square-o"></i> Save</button>
</div>

Getting ID of checked rows on a grid in javascript

I am displaying a grid with some data fetched from a csv file along with a checkbox before each row. I am also saving unique ID in the value property of checkbox. Now I want to get the value of ID`s of all checked check boxes in alert() when 'Cancel' button is clicked.
html-
<div class="panel panel-primary">
<div class="panel-heading">DIS Automation</div>
<div class="panel-body">
<div class="field_row">
<input type="file" accept=".csv" id="fileUpload" name="fileUpload1" />
</div>
<br />
<div class="field_row">
<div class="col-lg-12">
<div class="form-group">
<center><div class="col-lg-3"><div class="input-append" id="filterDev" style="visibility: hidden">
<input name="search" id="inputFilter" placeholder="Enter comma separated ID" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></div></center>
<div class="col-lg-6"></div>
<input type="button" id="upload" value="Upload" class="btn btn-primary" />
<input type="button" id="cancel" value="Cancel/Save" style="visibility: hidden" class="btn btn-primary" />
<input type="button" id="process" value="Process" style="visibility: hidden" class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style=" max-height:600px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
</div>
<div class="col-sm-3">
<p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("#cancel").on("click", function () {
$('input:checked').each(function () {
//$(this).closest("tr").remove();
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
$("#filter").click(function () {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
/* $("#File1").click(function () {
window.location = "Files/CommitteeMembers.xlsx";
});
$("#File1").click(function () {
window.location = "Files/GSD_Offering_Completion.xlsx";
});*/
</script>
Javascript-
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
//var table = $("<table id='name'/>");
var lines = e.target.result.split("\n");
//alert(lines);
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < headers.length; i++) {
var header = headers[i];
header = header.replace(/(\r\n|\n|\r)/gm, "");
headers[i] = header;
}
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
//alert(currentline);
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
//alert(obj[headers[j]]);
}
result.push(obj);
//alert(JSON.stringify(result));
}
//alert(result[0].NAME + ' '+ result[0].ADDRESS+" "+result[0].CITY);
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
});
});
function populateTable(finalObject) {
var obj = finalObject;
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = Object.keys(obj[0]);
columns.unshift('');
//alert(columns);
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html([columns[i]]);
row.append(headerCell);
}
$.each(obj, function (i, obj) {
row = '<tr data-id="' + obj.ID + '"><td><input type="checkbox" value='+obj.ID+'/></td>
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
How can this be implemented??
This is a sample code of how you can do it:
$(".btnCancel").click(function(){
var alertText="";
$("[type='checkbox']:checked").each(function(){
alertText+= $(this).attr("value") + " ";
});
alert(alertText);
});
Here is the JSFiddle demo

Unable to tigger elements inside the webui-popover

I am working on a app dashboard, where I am trying to add a jquery calculator inside webui-popover. the calculator is working fine outside the popover but when it is inside the popover div it is not working. The plugin author said "This problem is caused by that the plugin stop the event bubbling",
I do not have much knowledge about Jquery or Javascript, If anyone can help me with this it will be nice. So, is there any way to make the calculator work inside popover element?.
Calculator Script taken from HERE
Here is the codes
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>
Use dismissible:false
/* WEBUI SCRIPT*/
(function() {
var settings = {
trigger: 'click',
title: '',
width: 320,
multi: true,
closeable: false,
style: '',
delay: 300,
padding: true,
dismissible:false
};
function initPopover() {
var tableContent = $('#discalc').html(),
tableSettings = {
content: tableContent,
width: 298
};
$('a.showdisclac').webuiPopover('destroy').webuiPopover($.extend({}, settings, tableSettings));
}
initPopover();
})();
/* CALCULATOR */
$("document").ready(function() {
var key = null;
$(document).on("click", ".clean", function() {
$('.input').val("");
});
$(document).on("click", ".Show", function() {
var EText = $('#Result').val();
if (EText != "0") {
var val1 = EText;
var ButtonVal = $(this);
var val2 = ButtonVal.text();
var Res = val1 + val2;
$('#Result').val(Res);
} else {
$('#Result').val();
}
});
$(function(e) {
var interRes = null;
var operator;
$(document).on("click", ".operators", function(e) {
var value1 = $('#Result').val();
if (interRes != null) {
var result = ApplyOperation(interRes, value1, operator);
interRes = result;
} else {
interRes = value1;
}
operator = $(this).text();
$('input').val("");
});
$(document).on("keypress", "#Result", function(e) {
if ((e.keyCode == 61)) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
var data = value2.split("+");
if (data.length > 2) res = ApplyOperation(interRes, data[data.length - 1], op);
else res = ApplyOperation(interRes, data[1], op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
} else if ((e.keyCode == 43) || (e.keyCode == 45) || (e.keyCode == 42) || (e.keyCode == 47)) {
var value1 = $('#Result').val();
var inter = (interRes != null);
if (inter) {
var op = operator;
var data = value1.split("+");
if (data.length > 2) {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[data.length - 1], op);
interRes = result;
} else {
operator = String.fromCharCode(e.keyCode);
result = ApplyOperation(interRes, data[1], op);
interRes = result;
}
} else {
interRes = value1;
}
operator = String.fromCharCode(e.keyCode);
$('.input').text("");
}
});
$(document).on("click", "#Calculate", function(e) {
var op = operator;
var res;
var value2 = $('#Result').val();
if ((value2 != "")) {
res = ApplyOperation(interRes, value2, op);
} else {
res = interRes;
}
$('#Result').val(res);
interRes = null;
});
});
function ApplyOperation(value1, value2, operator) {
var res;
switch (operator) {
case "+":
res = addition(value1, value2);
break;
case "-":
res = subtraction(value1, value2);
break;
case "*":
res = multiplication(value1, value2);
break;
case "/":
res = division(value1, value2);
break;
}
return res;
}
function addition(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var total = a + b;
return total;
}
function subtraction(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var sub = a - b;
return sub;
}
function multiplication(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var product = a * b;
return product;
}
function division(first, second) {
var a = parseFloat(first);
var b = parseFloat(second);
var divi = a / b;
return divi;
}
});
<link rel="stylesheet" type="text/css" href="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.css"> .webui-popover-content {
padding: 0;
}
.webui-popover {
padding: 0;
border: none;
border: 0;
background: transparent;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.webui-popover.top>.arrow:after,
.webui-popover.top-right>.arrow:after,
.webui-popover.top-left>.arrow:after {
border-top-color: #525252;
}
.discalc {
display: none;
}
.disresform {
background: #525252;
padding: 20px 5px 20px 5px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-ms-border-radius: 6px;
-o-border-radius: 6px;
border-radius: 6px;
bottom: 0;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://sandywalker.github.io/webui-popover/dist/jquery.webui-popover.min.js"></script>
Discount
<div id="discalc" class="discalc">
<div class="disresform">
<h2>Simple Calculator</h2>
<input id="Result" class="input" value="0" />
<div id="keys">
<div id="FirstRow">
<button id="ClearAll" type="reset" value="CE" class="clean">CE</button>
<button id="Clear" type="reset" value="C" class="clean">C</button>
<button id="Add" type="button" value="+" class="operators operand">+</button>
</div>
<div id="SecondRow">
<button id="One" type="button" value="1" class="Show">1</button>
<button id="Two" type="button" value="2" class="Show">2</button>
<button id="Three" type="button" value="3" class="Show">3</button>
<button id="Sub" type="button" value="-" class="operators operand">-</button>
</div>
<div id="ThirdRow">
<button id="Four" type="button" value="4" class="Show">4</button>
<button id="Five" type="button" value="5" class="Show">5</button>
<button id="six" type="button" value="6" class="Show">6</button>
<button id="Mul" type="button" value="*" class="operators operand">*</button>
</div>
<div id="FourthRow">
<button id="Seven" type="button" value="7" class="Show">7</button>
<button id="Eight" type="button" value="8" class="Show">8</button>
<button id="Nine" type="button" value="9" class="Show">9</button>
<button id="Divide" type="button" value="/" class="operators operand">/</button>
</div>
<div id="FifthRow">
<button id="Zero" type="button" value="0" class="Show">0</button>
<button id="Dot" type="button" value="." class="Show">.</button>
<button id="Calculate" type="button" value="=" class="operand">=</button>
</div>
</div>
</div>
</div>

Basic Calculator - event binding using pure javascript

I am completely new to the Javascript .When I am looking to get the value to the button its get failed.I already given the setEvent.Like getEle();
And also bind the click function, Now i want to get the input values and perform mathematical calculations.
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div id="container" >
<div class="calculator">
<ul>
<li>
<div id="display">
<span id="math"></span>
<span id="number"></span>
</div>
</li>
<li>
<button class="input" value="7">7</button>
<button class="input" value="8">8</button>
<button class="input" value="9">9</button>
<button class="control" value="/">÷</button>
<button class="undo" value="-1">←</button>
</li>
<li>
<button class="input" value="4">4</button>
<button class="input" value="5">5</button>
<button class="input" value="6">6</button>
<button class="control" value="*">×</button>
<button class="clear">C</button>
</li>
<li>
<button class="input" value="1">1</button>
<button class="input" value="2">2</button>
<button class="input" value="3">3</button>
<button class="control" value="-">-</button>
<button class="control" value="%">%</button>
</li>
<li>
<button class="input size2" value="0">0</button>
<button class="input" value=".">∙</button>
<button class="control" value="+">+</button>
<button class="submit">=</button>
</li>
</ul>
</div>
</div>
</body>
<script type="text/javascript" src="calculator.js"></script>
</html>
javascript
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if(ele.length > 0) {
for (var i=0; i<ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if(_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
setEvent("click", ".input", function() {
console.log(this.value);
});
setEvent("click", ".control", function() {
console.log(this.value);
});
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if(ele.length > 0) {
for (var i=0; i<ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if(_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
function getInnerHtml(id) {
return document.getElementById(id).innerHTML;
}
function getValue(elem) {
return elem.value;
}
setEvent("click", ".input", function() {
console.log(this.value);
var _num = getInnerHtml("number");
_num = _num + "" + getValue(this);
document.getElementById("number").innerHTML = _num;
});
setEvent("click", ".control", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = _num1 + "" + this.value;
document.getElementById("number").innerHTML = _num1;
});
setEvent("click", ".clear", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = "";
document.getElementById("number").innerHTML = _num1;
});
setEvent("click", ".submit", function() {
console.log(this.value);
var _num1 = document.getElementById("number").innerHTML;
_num1 = eval( _num1 + "" + getValue(this));
document.getElementById("number").innerHTML = _num1;
});
Hope this will work out.
You can print the values to the screen by using document.getElementById("number").innerHTML = this.value.
Notie that it is not jquery, when calling getElementById you don't do("#id") only ("id"), JavaScript will match the string with the desired Id.
In jquery, it is much like the behavior of css, so in order to find ID you don't do getElementById instead, you just do
//$ means jquery
$("#id")
which is equivalent to java script's getElementById.

Categories