How to create a total using plus minus buttons and input box - javascript

Im trying to make a price calculator where 1 employee = $21 a month. There are two way I want to be able to set the quantity of employees. I would like to use a plus and minus sign to adjust the quantity as well as have an input box where they can type the quantity. Adjusting either will instantly update the total. In my attached code you will see that the typing a number into the input box works correctly but using the plus and minus sign does not adjust the total. It changes the number but the math is not executed. Does anyone have any ideas? Thank you!
var $buttonPlus = $('.increase-btn');
var $buttonMin = $('.decrease-btn');
var $quantity = $('.quantity');
/*For plus and minus buttons*/
$buttonPlus.click(function(){
$quantity.val( parseInt($quantity.val()) + 1 );
});
$buttonMin.click(function(){
$quantity.val( parseInt($quantity.val()) - 1 );
});
/*For total*/
$(document).ready(function(){
$(".checkout").on("keyup", ".quantity", function(){
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("$" + price * quantity);
})
})
.checkout {
height: 300px;
width: 400px;
margin: 20px auto;
border: 2px solid black;
text-align: center;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="checkout">
<h1 class="title">Checkout</h1>
<p class="price" data-price="21">$21 per month</p>
<p class="description">Quantity:</p>
<button type="button" class="decrease-btn">-</button>
<input type="text" class="quantity" value="1">
<button type="button" class="increase-btn">+</button>
<p class="total">Total: <span id="total">$21</span></p>
</div>

Change the event to 'input' so it only fires for actual value changes
Add trigger('input') to the end of the value changes so the event is generated (logical value changes do not generate events).
Move the first bindings into the document ready for safety (optional change).
Put Math.max() around the subtraction so that the negative can not make the value go less than zero. (optional change)
/*For total*/
$(document).ready(function() {
$(".checkout").on("input", ".quantity", function() {
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("$" + price * quantity);
})
var $buttonPlus = $('.increase-btn');
var $buttonMin = $('.decrease-btn');
var $quantity = $('.quantity');
/*For plus and minus buttons*/
$buttonPlus.click(function() {
$quantity.val(parseInt($quantity.val()) + 1).trigger('input');
});
$buttonMin.click(function() {
$quantity.val(Math.max(parseInt($quantity.val()) - 1, 0)).trigger('input');
});
})
.checkout {
height: 300px;
width: 400px;
margin: 20px auto;
border: 2px solid black;
text-align: center;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="checkout">
<h1 class="title">Checkout</h1>
<p class="price" data-price="21">$21 per month</p>
<p class="description">Quantity:</p>
<button type="button" class="decrease-btn">-</button>
<input type="text" class="quantity" value="1">
<button type="button" class="increase-btn">+</button>
<p class="total">Total: <span id="total">$21</span></p>
</div>

Related

jQuery .append() and .remove() skipping behavior with slider function

I'm having trouble with some dynamic HTML. I've got a slider that adds or removes DOM elements as the value changes. Each time it increases, an element is added, and each time it decreases, an element is removed.
Here's the HTML:
<input type="range" min="3" max="16" class="rgb-slider" value="3" tabindex="-1" oninput="slider(this.value)">
<div class="container">
<div class="boxes">
<div class="box"><span></span></div>
<div class="box"><span></span></div>
<div class="box"><span></span></div>
</div>
</div>
Here's the JS:
var colorCount = 3;
function slider(value) {
if (colorCount < parseInt(value)) {
$('.boxes').append('<div class="box"><span></span></div>');
colorCount = value;
} else {
$('.box:last-child').remove();
colorCount = value;
}
}
http://jsfiddle.net/meu9carx/
However, when I quickly move the slider, it seems to skip or trip up, and I end up with more or fewer than I started with. The slider has a range from 3-16, but sometimes the min value goes to more or less than 3. Sometimes, all the boxes vanish.
Is there a smarter way to code this? I'm trying to avoid hard-coding divs here.
If the mouse moves fast, it's possible for the input value to change by more than one (in either direction) during a single input event. Use the value in the input to determine how many squares there should be exactly, rather than adding or removing only a single element each time.
const boxes = $('.boxes');
$('input').on('input', function() {
const targetSquares = Number(this.value);
while (boxes.children().length < targetSquares) {
boxes.append('<div class="box"><span></span></div>');
}
while (boxes.children().length > targetSquares) {
$('.box:last-child').remove();
}
});
body{
background: #777;
font-family: 'Arimo', sans-serif;
}
.container { padding: 20px 0; }
.boxes { display: flex; }
.box {
padding: 10px;
background: #ffffff;
height: 100px;
flex: 1;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="3" max="16" class="rgb-slider" value="3" tabindex="-1">
<div class="container">
<div class="boxes">
<div class="box"><span></span></div>
<div class="box"><span></span></div>
<div class="box"><span></span></div>
</div>
</div>

Range slider with min and max values limites

I have this code, which displays a range slider with values from 1 to 100 and 4 squares of different values, i have the minimum value limite handler on the range line, as i increase the value using the handler, the squares that are bellow that value start the disapeer.
Now i want to add the maximum handler limite on the same line. ( One line with 2 handlers )
Anybody knows how ?
Thanks.
function sliderChange(val) {
document.getElementById('sliderStatusMin').innerHTML = val;
function displayItem(val) {
$('.item').filter(function() {
var price = $(this).data('price');
if (price < val) {
return price;
}
}).hide();
$('.item').filter(function() {
var price = $(this).data('price');
if (price > val) {
return price;
}
}).show();
}
displayItem(val);
}
.item {
width: 100px;
height: 100px;
background-color: red;
}
<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
</script>
<input class="first" type="range" min="0" max="100" value="50" step="2" onChange="sliderChange(this.value)" />
<br /><br /> Minimum Value = <span id="sliderStatusMin"></span>
<div class="item" data-price="90">90</div>
<div class="item" data-price="20">20</div>
<div class="item" data-price="70">70</div>
<div class="item" data-price="40">40</div>
Take a look at the jQuery UI http://jqueryui.com/slider/#range
or
take a look at this answer https://stackoverflow.com/a/31083391/7993505 for a variant without jQuery UI.

Get input value and generate multiple textarea and set value there

I have a DOM like this, when i fill the input field and click the button i need to create a textarea element and and stored the input value there.
if i click multiple times create multiple textarea and multiple ID's, How can i do this please check my code, Best answers must be appreciated
$('#note').on('click', function(){
var storedNoteVal = $('#enterVal').val();
var count_id = 1;
var noteCov = $('.note_cover');
$('#content_bag').prepend('<div class="full-width note_cover" id="noteId"><textarea></textarea></div>');
$(noteCov).find('textarea').val(storedNoteVal);
$(noteCov).each(function(index, element) {
$(this).attr('id', 'noteId' + count_id);
count_id++;
});
});
.full-width.note_cover {
float: left;
margin-bottom:15px;
}
.note_cover textarea {
height: auto !important;
height: 45px !important;
resize: none;
width: 100%;
/*border:none;*/
}
<div class="col-md-11 col-md-offset-1 col-sm-8 col-xs-12 mtp" id="content_bag">
</div><!-- #content_bag -->
<input type="text" placeholder="Enter project Tags" class="majorInp" id="enterVal" />
<button id="note">click me</button>
Your code is working fine, just put storedNoteVal in text-area, and input won't generate any text-area if its blank.
$('#note').on('click', function() {
var storedNoteVal = $('#enterVal').val();
var count_id = 1;
var noteCov = $('.note_cover');
if(storedNoteVal){
$('#content_bag').prepend('<div class="full-width note_cover" id="noteId"><textarea>' + storedNoteVal + '</textarea></div>');
//$(noteCov).find('textarea').val(storedNoteVal);
$(noteCov).each(function(index, element) {
$(this).attr('id', 'noteId' + count_id);
count_id++;
});
}
});
.full-width.note_cover {
float: left;
margin-bottom: 15px;
}
.note_cover textarea {
height: auto !important;
height: 45px !important;
resize: none;
width: 100%;
/*border:none;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-md-11 col-md-offset-1 col-sm-8 col-xs-12 mtp" id="content_bag">
</div>
<!-- #content_bag -->
<div>
<input type="text" placeholder="Enter project Tags" class="majorInp" id="enterVal" />
<button id="note">click me</button>
</div>
Building on Abhinshek answer -
Your code actually reassign id's to the textareas, since you loop through all the elements after prepending them.
You could define count_id as a window variable (outside the click function) and then just use it.
Also, you don't need to wrap noteCov with $() since $('.note_cover') returns a jQuery objects array
var count_id = 1;
$('#note').on('click', function() {
var storedNoteVal = $('#enterVal').val();
$('#content_bag').prepend('<div class="full-width note_cover" id="noteId_'+count_id+'"><textarea>' + storedNoteVal + '</textarea></div>');
count_id++;
});
This way each textarea gets it's own unique id that doesn't change

Array converted into a string is used to be converted into a number but does not work

I am building a calculator with HTML, CSS and and pure JavaScript.
I tried to do it just with little information, but I cannot understand what is happening now. Since a person type many digits (i.e 456) to create a number and then click on the operator, I decided to create an array(arrayInput) that will hold the numbers 4,5,6 and even the character "." So for instance 4.56 in the array appears as 4,.,5,6 so I removed the characters and then the whitespaces. Finally since it is now a string "4.56" I used Number() function to convert it to number. I also used parseInt, parseFloat, but it only displays the first time and when an operator is selected, then it does not calculate the total, but remains with the total zero. I will appreciate your support.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<style type='text/css'>
.row{
height: 2em;
width: 25%;
border: 0.05em solid black;
float:left;
font-size: 2em;
font-style: sans-serif;
text-align:center;
padding:0;
}
#screen{
height: 4em;
width: 100%;
border: 0.03em solid black;
float:left;
font-size: 3em;
font-style: sans-serif;
text-align:right;
margin:0;
padding:0;
}
</style>
<script type='text/javascript'>
var total=0; //which will replace the number1 in parameters
var numberArray=[];
var operator="plus"; //by default i give it an addition
var number=0;
//get digits from buttons to create the number you want to use
var performOperator=function (tot,num,ope){
if(ope==="plus")
{
tot+=num;
num=0;
document.getElementById("screen").innerHTML = tot; //display a number of total HOPEFULLY
}
else if(ope==="-")
{
tot-=num;
num=0;
document.getElementById("screen").innerHTML = tot; //display a number of total HOPEFULLY
}
else if(ope==="multiply")
{
tot*=num;
num=0;
document.getElementById("screen").innerHTML = tot; //display a number of total HOPEFULLY
}
else if(ope==="/")
{
tot/=num;
num=0;
document.getElementById("screen").innerHTML = tot; //display a number of total HOPEFULLY
}
else if(ope==="equal")
{
document.getElementById("screen").innerHTML = tot; //display a number of last total HOPEFULLY
num=0;
}
else if(ope==="clear")
{
tot=0;
num=0;
document.getElementById("screen").innerHTML = tot; //display a number of total HOPEFULLY
}
}
function getDigit(elemId){
var digitEntry=document.getElementById(elemId).value; //digit value goes to "val"
numberArray.push(digitEntry); //each val should go to push into an array
var numberWithSpace=numberArray.join(' '); //convert the array into a string block with spaces
var numberNoSpace=numberWithSpace.replace(/\s/g, ''); //string number with no space
number=Number(numberNoSpace);// it should be converter into a number here but does not look like..
document.getElementById("screen").innerHTML = number; //probably displays array of Number as STRING
}
function highlightSign(elemId){
var sign=document.getElementById(elemId).value; //digit value goes to "sign""
operator=sign;
performOperator(total,number,operator); //Call the performOperator function and creates new total and new number 0
numberArray=[]; //once the number is created as real number then the array used to built it clears
}
</script>
</head>
<body>
<body>
<p id="screen"></p>
<button id="nC" class="row" value=""></button>
<button id="pmSign" class="row" value=""></button>
<button id="nPercentage" class="row" value=""></button>
<button id="divide" class="row" value="/" onclick="highlightSign(this.id)">/</button>
<button id="n7" class="row" value=7 onclick="getDigit(this.id)">7</button>
<button id="n8" class="row" value=8 onclick="getDigit(this.id)">8</button>
<button id="n9" class="row" value=9 onclick="getDigit(this.id)">9</button>
<button id="opX" class="row" value="multiply" onclick="highlightSign(this.id)">x</button>
<button id="n4" class="row" value=4 onclick="getDigit(this.id)">4</button>
<button id="n5" class="row" value=5 onclick="getDigit(this.id)">5</button>
<button id="n6" class="row" value=6 onclick="getDigit(this.id)">6</button>
<button id="minus" class="row" value="-" onclick="highlightSign(this.id)">-</button>
<button id="n1" class="row" value=1 onclick="getDigit(this.id)">1</button>
<button id="n2" class="row" value=2 onclick="getDigit(this.id)">2</button>
<button id="n3" class="row" value=3 onclick="getDigit(this.id)">3</button>
<button id="plus" class="row" value="plus" onclick="highlightSign(this.id)">+</button>
<button id="n0" class="row" value=0 onclick="getDigit(this.id)">0</button>
<button id="clear" class="row" value="clear" onclick="highlightSign(this.id)">clear</button>
<button id="decPoint" class="row" value="." onclick="getDigit(this.id)">.</button>
<button id="equal" class="row" value="equal" onclick="highlightSign(this.id)">=</button>
</body>
</body>
</html>
I made your total work here. But you need to change the logic of your calculator. There's a lot to change there
http://jsfiddle.net/g6gj1kr6/9/
Don't pass your total as parameter just make it global, then you can rewrite it.
var tot=0;
Anyway, there is a lot of work to do for your calculator

JavaScript application is not calculating, please?

I am a beginner at JavaScript and I have been working on this very simple project for a couple of days. It is supposed to allow you to calculate the area and perimeter of a rectangle, but despite how much I tweaked the code, it will not calculate when I enter numbers. It should just be a simple user interface that allows you to input into two text boxes:
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var width = parseFloat($("width").value);
var length = parseFloat($("length").value);
$("area").value = "";
$("perimeter").value = "";
if (isNaN(width) || width <= 0) {
alert("Width must be a valid number and greater than zero.");
}
else if (isNaN(length) || width <= 0) {
alert("Length must be a valid number and greater than zero.");
} else {
var area = width * length;
var perimeter = 2 * width + 2 * length;
$("area").value = area;
$("perimeter").value = perimeter;
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("length").focus();
}
}
body {
font-family: Arial, Helvetica, sans-serif;
background: #333366; }
#content {
width: 450px;
margin: 10px auto;
padding: 5px 20px;
background: white;
border: thin solid black; }
#salesTax, #total {
color: black; }
#taxCalc label {
display: block;
width: 6em;
text-align: right;
padding-right: 1em;
float: left; }
#taxCalc input {
display: block;
float: left; }
#taxCalc br {
clear: left; }
​
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Area and Perimeter Calculator</title>
<link rel="stylesheet" type="text/css" href="sales_tax.css" />
<script type="text/javascript" src="sales_tax.js"></script>
</head>
<body>
<div id="content">
<h2>Area and Perimeter Calculator</h2>
<p>Enter the values below and click "Calculate".</p>
<div id="taxCalc">
<label for="length">Length:</label>
<input type="text" id="length" /><br />
<label for="width">Width:</label>
<input type="text" id="width" /><br />
<label for="area">Area:</label>
<input type="text" id="area" disabled="disabled" /><br />
<label for="perimeter">Perimeter:</label>
<input type="text" id="total" disabled="disabled" /><br />
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</div>
</body>
</html>
​
If anyone can please help even a little, I would genuinely appreciate it,
Thank you.
There were two problems with your script (Well technically three, but I think the missing v at the beginning was a copy/paste mistake.
1st: The window.onload functions needs to be outside calculate_click. It never gets called, because the calculate_click never gets called.
2nd: The input for perimeter, had id="total", but you were calling $("perimeter"). This is fixed in the jsfiddle.
Here is a working form.

Categories