Jquery - Adding Input value and another number together if checkbox is checked - javascript

Im creating a form where i want the user to fill out an amount, and then show at the bottom of the form. Then if there is a checkbox checked it adds 21 to the value within the input field so far i have this, but its not quite working.
http://jsfiddle.net/vePbV/
<label>Desired amount</label> <input name="tbDesiredAmount" type="number" id="tbDesiredAmount" min="50" />
<label>Include Apron?</label> <input id="cb_Apron" type="checkbox" name="cb_Apron" />
<p>Total: £<span id="total">0</span>.00</p>
$('#tbDesiredAmount').blur(function() {
var value = $('#tbDesiredAmount').val();
$("#total").empty().append(value);
});
$('#cb_Apron').blur(function() {
var value = $('#tbDesiredAmount').val();
var apron = 21;
var total = value + apron;
$("#total").empty().append(total);
});
So and example of what i want it to do.
Type 70 into "desired amount", show 70 in #total when you focus off the input field.
Check apron tickbox, adds 21 to the desired amount so displays 91 in #total
if you uncheck the apron checkbox, it will remove 21 from the figure in #total
if i change the desired amount, it will update the #total, this needs to work with the tickbox checked and the tickbox not checked.
Any help would be greatly appreciated as im rather stuck at the moment.

Try this Use parseInt()
var apron = 21;
$('#tbDesiredAmount').keyup(function () {
var value = $('#tbDesiredAmount').val();
if ($('#cb_Apron').is(':checked')) {
var total = parseInt(value) + parseInt(apron);
$("#total").empty().append(total);
} else {
$("#total").empty().append(value);
}
});
$('#cb_Apron').click(function () {
if ($(this).is(':checked')) {
var value = $('#tbDesiredAmount').val();
var total = parseInt(value) + parseInt(apron);
$("#total").empty().append(total);
} else {
var tot = parseInt($("#total").text()) - (parseInt(apron))
$("#total").empty().append(tot);
}
});
DEMO

Related

HTML, Incrementing input value with jquery

I want to increase the value entered in the amount input by 10% in real time and show it in the amount + commission input, how can I do it? I will be glad if you help me thank you
Using jQuery, read the input value on change and then calculate the final amount after commission and display it in the second input field which will be disabled.
$('input').on( "input", function() {
console.log( $( this ).val() );
let val = parseInt($(this).val());
let comm = 10;
let total = val + val*comm/100;
$('input[name="total"]').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="amount"/>
<input type="text" name="total" disabled />
You need to provide the code you have so we can help you.
However, you can make this with Jquery using .change() method
let amount = 0;
let amountPlusCommission = 0;
const commission = 0.1;
$("#yourinputID").change(function () {
const value = $(this).val();
amount = value;
amountPlusCommission = value + (value * commission);
$("#yourSecondinputID").val(amountPlusCommission);
});
Change the yourinputID with the first input ID and yourSecondinputID with the result input ID.
EXTRA: .keyup() function is much better for this
$("#yourinputID").keyup(function () {...})
.change() detects when the input changes, but .keyup() detects when the user releases a key on the input and is much more efficient.

Troubleshooting JS conditional

I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when clicked changes the amount to $5. I'm trying to get get it so that if say the user tries to enter a number such as 10, 15 or 20 as examples it will allow them to type it. Currently it is converting anything less than 5 for the starting number to 5 which makes it impossible.
$("#donrAmountInput").on("input", function() {
setDonrAmount("Other");
});
function setDonrAmount(id) {
var amt;
$('#donrAmountButtons .active').removeClass('active');
if (id == "Other") {
amt = $("#donrAmountInput").val() > 5 ? $("#donrAmountInput").val() : 5;
$('#otherAmount button').addClass('active');
}
else {
amt = id.substring(10);
$('#donrAmount' + amt).addClass('active');
}
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp
You can set your input type to number specify min,max,required attributes and then check the validity of it via javascript/jQuery.
function myFunction() {
var inpObj = $("#id1")[0];
if (inpObj.checkValidity() === false) {
$("#demo").html(inpObj.validationMessage);
} else {
$("#demo").html(inpObj.value);
}
}
$('button').on('click',function(){
myFunction();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" type="number" min="5" max="300" required>
<button>OK</button>
<p id="demo"></p>

Javascript calculation returns 'on' when calculating percentage of variable

I constructed a calculation form out of different modules and got it to work except for 1 element.
The overall calculation is build up as (value + value = total), and the values are all regular numbers.
However, the last bit I added is a 'percentage'-value which is 10% of the first value in the form. So as an example:
Value 1 = 50,
Percent value 2 = 5 (10% of value 1),
Total = 55
In my code this looks as follows:
var NonTrans_prices = new Array();
NonTrans_prices["NoneNon"] = 0;
NonTrans_prices["LemonNon"] = 5994;
NonTrans_prices["CustardNon"] = 7076;
function NonTrans() {
var NonTransPrice = 0;
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
NonTransPrice = NonTrans_prices[selectedFilling.value];
return NonTransPrice;
}
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
function optionprice1() {
var inscriptionPrice = 0;
var theForm = document.forms["GRANADANEO"];
var optionprice = theForm.elements["optionprice"];
if (optionprice.checked == true) {
inscriptionPrice = optionprice.value;
}
return inscriptionPrice;
}
function calculateTotal() {
var cakePrice = NonTrans() + optionprice1();
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total Price: " + cakePrice + " \u20ac";
}
*The NonTransPrice is connected to a dropdown box, and the optionprice1 is connected to a checkbox.
As soon as I tick the checkbox containing the 10% value, the letters "on" are added to the total price. What's going wrong?
**Sorry forgot to post the entire code so that you guys/girls can test: https://jsfiddle.net/6a55tm4j/
For some reason it doesn't show the total value in jsfiddle, on the live website I am testing on it does so that's not really a problem I am facing live.
Live link: http://axesseurope.be/appalacarte/Calculator/axess_calculator.html
This is the HTML code containing the parts affected by the .js code:
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="GRANADANEO" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<table><tr><td>
<label >NonTrans</label>
<select id="NonTrans" name='NonTrans' onchange="calculateTotal()">
<option value="NoneNon">Select Dimensions</option>
<option value="LemonNon">3,00 6,40 0,85</option>
<option value="CustardNon">3,00 7,50 0,85</option>
</select>
</td></tr></table>
<hr>
<br/>
<label>Granada Neo Opties Algemeen</label>
<p>
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
<label for='optionprice' class="inlinelabel">optionprice</label>
</p>
<p>
<input type="checkbox" id="SchuifdeurVoorzijde" name='SchuifdeurVoorzijde' onclick="calculateTotal()" />
<label for='SchuifdeurVoorzijde' class="inlinelabel">Schuifdeur in voorzijde</label>
</p>
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
In the end with the help of Scott Marcus this was the solution:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
var lstNonTransValue = NonTrans_prices[selectedFilling.value];
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[selectedFilling.value];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
Checkboxes have a value of "on" when they are selected. Ensure that your checkboxes include a value attribute that contains the meaningful data they represent. For example:
<input type="checkbox" id="chkSomeId" name="chkSomeID"
value="someValueToBeWhenChecked">
This is true of radio buttons as well.
So, in your code, this line:
inscriptionPrice = optionprice.value
is most-likely accessing the value of either a checkbox or radio button that does not have an explicit value set for it, but is checked.
Also, remember that all values pulled from HTML come into JavaScript as strings, so if you need to do math with those values, you'll want to use parseInt() and parseFloat().
UPDATE: now that you have posted your HTML, I see this:
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
which is exactly what I suspected. My above answer will correct the problem. That checkbox needs a value set for it.
UPDATE:
In your following code:
//Add percentage
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
//Add percentage
function optionprice1()
{
var inscriptionPrice=0;
//Get a refernce to the form id="GRANADANEO"
var theForm = document.forms["GRANADANEO"];
//Get a reference to the checkbox id="optionprice"
var optionprice = theForm.elements["optionprice"];
//If they checked the box set inscriptionPrice to 20
if(optionprice.checked==true){
inscriptionPrice=optionprice.value;
}
//finally we return the inscriptionPrice
return inscriptionPrice;
}
I think that you should take the 4 var lines and include them in the function.
I think that the first line: var price = NonTrans_prices; is incorrect, because it sets the variable price to the actual array of NonTrans prices, rather than looking up a particular price, which would be:
var price = NonTrans_prices[document.getElementById("nonTransList").value];
Then, your problem is that if the optionPrice checkbox is checked, you are trying to access the value of the checkbox, which (as I've said) doesn't explicitly exist, so you get "on" (because the checkbox is checked). What you should be doing is setting the price to result of the 10% calculation that was just done on the line above. So the final function looks like this:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var lstNonTransValue = document.getElementById(NonTrans).value;
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[lstNonTransValue];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
You were close, but the thing that, I think, tripped you up was that you created a variable with the same name as your checkbox and after doing the calculation, you should have been trying to get the value of your variable, but you were trying to get the value of the checkbox, which isn't where the answer was.
I hope that I've understood what you wanted correctly, but even if my algorithm is off, I hope you can see that you don't want to be using the value of the checkbox to get your answer, since it doesn't store any value.

How do I increment the value of an input of type=number using jQuery?

I'm trying to increment the value of an input type="number" element using jQuery. However I currently have it so that every time I press the add button it appends 1 to the value so I get a value like 1111 etc etc...
I was able to do it fine when it was set to type=text but it was not ideal as I was trying to increment the values so all that was happening was the counter was being appended to the value of the input box. Output was like this 01 02 03 04.
Currently, I'm doing this:
HTML
<input type="number" class="qty" id="book-qty" disabled/>
<span class="add">ADD</span>
jQuery
var count = 0;
$('.minus').click(function () {
if (count - 1 >= 0) {
count = parseInt($(this).parent().find('#book-qty').val());
count = count - 1;
$(this).parent().find('#book-qty').val(count);
} else {
alert('Nothing to take away!');
}
});
$('.add').click(function () {
count = $(this).parent().find('#book-qty').val();
count = count + 1;
$(this).parent().find('#book-qty').val(count);
});
I have a JSFiddle I'm working on here:
https://jsfiddle.net/javacadabra/L1sLr921/
Does anyone know?
jsfiddle demo
you need to parse the value to an integer otherwise it get treated as a string so it will concatenate instead of add together.
count = parseInt($('#book-qty').val());
Also you need to specify a default value for your inputs like stated by Mex.
Set the default value to 0 with "value=0" on the input type=number.
Then use:
count = parseInt(count) + 1;
instead of:
count = count + 1;

Format Numbers in JavaScript

I have a web page that allows a user to enter values into fields. When a user updates a field, I want to automatically update the total displayed to the user. Because the input fields are dynamically generated, I created a JavaScript function called "update". A sample of my code is shown here:
<input type="text" id="myField1" onchange="return update(this);" />
<input type="text" id="myField2" onchange="return update(this);" />
<span id="totalCount"></span>
var total = 0;
function update(e) {
var v = $(e).val();
if (parseInt(v) != NaN) {
total = total + v;
$("#totalCount").html(total);
}
return false;
}
When a user enters "2" into "myField1", "02" is displayed in the "totalCount" element. In reality, I would like to just display "2". How do I do this in JavaScript while taking into a account odd entries?
Thanks!
Since $(e).val() is a string, total + v is a string too. Use parseInt not just for the test but also when using the value:
var v = parseInt($(e).val(), 10);
if (!isNaN(v)) {
total = total + v;
$("#totalCount").html(total);
}

Categories

Resources