Javascript for counting the values of text input fields - javascript

I am trying to create a hotel booking form with an increment counter which I have already setup. Its got 3 input fields and at the end there is a "group total" text input field. I need to ask if anyone could help me with the JS in order to counter the number of individuals in the total group box for when they incrementally add people in the 3 increment counters?
My code is as follows:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
textbox.value++;
}
function decrease() {
var textBox = document.getElementById("text");
textBox.value--;
}
function increase2() {
var a = 1;
var textbox2 = document.getElementById("text2");
textbox2.value++;
}
function decrease2() {
var textBox2 = document.getElementById("text2");
textBox2.value--;
}
function increase3() {
var a = 1;
var textbox3 = document.getElementById("text3");
textbox3.value++;
}
function decrease3() {
var textBox3 = document.getElementById("text3");
textBox3.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease()">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease2()">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase2()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease3()">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase3()">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="">
</a>

You can simplify your code by adding this to all onclick function calls so we can know which element called the function and with that we can figure out it's parent along with the correct input element to increment. In the end we call the increaseTotal() or decreaseTotal() function to update the group total field.
Note: I'm guessing you don't want to be able to decrease a field beyond 0, so I added that constraint as an if statement in the decrease() function. I also made the totalPersons input field's value to default to 3 because all of the 3 other inputs default to 1.
Run and test:
function increase(el) {
var textbox = el.parentElement.querySelector('input');
textbox.value++;
increaseTotal();
}
function decrease(el) {
var textBox = el.parentElement.querySelector('input');
if(textBox.value > 0) { // <- if value is at least 1
textBox.value--;
decreaseTotal();
}
}
function increaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value++;
}
function decreaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="3">
</a>

You could just increase/decrease the value attribute of the totalpersons element within the increase/decrease methods as well.
For example:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
var totalpersons = document.getElementById("totalPersons");
textbox.value++;
totalpersons.value++;
}

Note that the values of text boxes are always strings in javascript. The parseInt() function will convert them to integers.
https://jsfiddle.net/y473L1bt/2/
function updateTotal() {
var textbox = document.getElementById("text");
var textbox2 = document.getElementById("text2");
var textbox3 = document.getElementById("text3");
var total = document.getElementById("totalPersons");
total.value = parseInt(textbox.value) +
parseInt(textbox2.value) + parseInt(textbox3.value);
}
function increase(id) {
var textbox = document.getElementById(id);
textbox.value++;
updateTotal();
}
function decrease(id) {
var textBox = document.getElementById(id);
var a = textBox.value - 1;
if (a >= 0) {
textBox.value = a;
}
updateTotal();
}

Related

How to add and remove items from array with a text input field

I am trying to make a simple grocery list program. There is an add item and a remove item button. There is also a textbox. For example, when you type ‘apples’ into the text field and hit the add button. The add button should then put ‘apples’ in groceryList Array and then display apples in the div area labeled groceryinfo.
The remove button also won’t work. For example, if you have five different items in the list if the value entered into the text field is ‘apples’. Apples should be found and then removed. The groceryList array should then redisplay and show the array contains without the deleted item.
<body>
My grocery list
<br>
<br>
<div id="groceryinfo"></div>
<br>
<br>
<input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
<br>
<input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
<script>
var groceryList = [];
var groceryitem;
var description;
description = document.getElementById("groceryinfo");
function Add() {
groceryitem = document.getElementById('Text1').value;
groceryList.push(groceryitem);
groceryList = description;
}
function Remove() {
for (var i = 0; i <= groceryList.length; i++) {
if (groceryList[i] == groceryitem) groceryList.splice(i, 1);
groceryList = description;
}
}
</script>
You can achieve this with document.getElementById("groceryinfo").innerHTML like so:
<body>
My grocery list
<br>
<br>
<div id="groceryinfo"></div>
<br>
<br>
<input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
<br>
<input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
<script>
var groceryList = [];
var groceryitem;
var description;
description = document.getElementById("groceryinfo");
function Add() {
groceryitem = document.getElementById('Text1').value;
groceryList.push(groceryitem);
document.getElementById("groceryinfo").innerHTML = groceryList.toString();
}
function Remove() {
for (var i = 0; i <= groceryList.length; i++) {
if (groceryList[i] === groceryitem) {
groceryList.splice(i, 1);
document.getElementById("groceryinfo").innerHTML = groceryList.toString();
}
}
}
</script>

How to change the value of an Input control when the text of another Input control is changed?

I need the following output as shown in the gif below.
I created three inputs which I put in the box below. How can I have such output?
Please help with an example
NOTE:Suppose we have 50 inputs and the class is the same
I can't use it after Get ID
MY HTML code
<span class="pricing-heading">Your sale price:</span><div class="pricing-field"><input class="pricing-set-price" type="number" value="24.00"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span><div class="pricing-field"><input class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span><div class="pricing-field"><input class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
JS code :
$(".pricing-set-price").change(function(){
var item_rrp = $(this).val();
var item_base = $(this).parent().parent().parent().find('.pricing-base-price').val();
var profit = item_rrp - item_base;
var profit_format = profit.toFixed(2);
$(this).parent().parent().parent().find('.pricing-profit').val(profit_format);
});
You may try like
$(".pricing-set-price").change(function(){
let currentValue = $(this).val();
var previousValue = this.defaultValue;
if(previousValue < currentValue){
this.defaultValue = currentValue;
console.log('Increment');
}else{
console.log('Decrement');
}
});
You can call the function that changes the value of Profit (input) on the onchange , oninput, or onClick events of the SalePrice(input)
function increment() { document.getElementById('salePrice').stepUp();
calculateProfit()
}
function decrement() {
document.getElementById('salePrice').stepDown();
calculateProfit()
}
function calculateProfit(){
let sp = document.getElementById("salePrice").value;
document.getElementById("profit").value = sp - 10;
}
<input id="salePrice" type=number value=10 min=10 max=110 />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<br/>
Base Price :: <input type="text" id="basePrice" value=10
disabled >
<br/>
Profit :: <input type="text" id="profit" value=0 />
For more info about:
stepUp()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
stepDown()
https://www.w3schools.com/Jsref/met_week_stepdown.asp
Hi i think this might help. use id for your input fields.
function calculateProfit(val){
var baseCost = document.getElementById("baseCost").value;
document.getElementById("Profit").value = (val - baseCost).toFixed(2);
}
<div class="prt-pricing-heading">
<span class="pricing-heading">Your sale price:</span>
<div class="pricing-field"><input id="SalePrice" class="pricing-set-price" type="number" value="24.00" onchange="calculateProfit(this.value);" oninput="calculateProfit(this.value)"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span>
<div class="pricing-field"><input id="baseCost" class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span>
<div class="pricing-field"><input id="Profit" class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
For More info regarding:
oninput() https://www.w3schools.com/tags/att_oninput.asp
onchange() https://www.w3schools.com/tags/ev_onchange.asp

I cannot get the javaScript to do the function i am requesting it to do, in my case multiply two values by a hidden and then add a final value

I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>

Javascript not incrementing a variable

I would like to keep count every time the user clicks a the add row button. Here's the code I have that's not working.
function add_more_row() {
var rows_count = ParseInt(document.getElementById("rows_count").value);
rows_count += 1;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
What am I doing wrong?
Your code only gets the value and increases it, does not assign the value to the input field. Add this line after the increment statement:
document.getElementById("rows_count").value = rows_count;
Also it's parseInt() with lowercase p not ParseInt().
function add_more_row() {
var inputRow = document.getElementById("rows_count"),
rows_count = parseInt(inputRow.value);
rows_count += 1;
inputRow.value = rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
function add_more_row() {
var rows_count = parseInt(document.getElementById("rows_count").value);
rows_count += 1;
document.getElementById("rows_count").value= rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
It is because you declare the variable inside the function.
So, the variable does not increase.
var rows_count=ParseInt(document.getElementById("rows_count").value);
function add_more_row()
{
rows_count += 1;
}

How do I use javascript or jquery to find a sum and product of values from a forms field inputs?

How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>

Categories

Resources