I have 2 products and wanted to multiply with quantity and add up both price along with tax and to show the final price of both added and multiplied values I tried doing using jQuery but I am unable to multiply and add up both values can any one help me out
Here is the code for it:
$(document).ready(function(){
$('#sticker01').on('keyup', function() {
var sticker_01 = $('#sticker01').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_01 * 8 +1.30) + oldval;
$('#order_total').html(total_val);
});
});
$(document).ready(function(){
$('#sticker02').on('keyup', function() {
var sticker_02 = $('#sticker02').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_02 * 2 + 1.30) + oldval;
$('#order_total').html(total_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $<div id="order_total">0.00</div></span>
</div>
Here is a less verbose solution to your issue with minor changes to the HTML and a complete overhaul of the Javascript.
HTML:
I added the min attribute and set its value to 0 to prevent the input spinners from selecting negative values in both the sticker01 and sticker02 elements. I also set the order_total input to disabled as this is the calculation field which will get its value from the inline Javascript. These udpates are cosmetic and play no roll in the structural performance your app.
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
Javascript:
Here you can implement an anonymous function to handle the events .keyup() and .change() and use a delegated event on the input elements.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
That's everything you need. Here is a sample Code Snippet for your review.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
Related
My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>
I'm trying to calculate the %share which is simply an addition of share1+share2 == 100. However, I want it to work only on the two checked checkboxes.
How do I go about detecting the selected checkbox and apply the function accordingly?
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$("#share1").focusout(function() {
var share1 = $("#share1").val();
var answer = 100 - share1;
$("#share2").val(answer);
});
$("#share2").focusout(function() {
var share2 = $("#share2").val();
var answer = 100 - share2;
$("#share1").val(answer);
});
label {
display: block;
}
.block {
background-color: #eee;
padding: 15px;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<h6>You can choose a maximum of 2 users</h6>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share1" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share2" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share3" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share4" class="form-control" placeholder="% share" required>
</div>
</div>
Do you have a specific reason to use focusout?
You could catch the ID's of the two "selected" elements inside your checkbox function. Or to be precise, get id of input that is in the next div inside the clicked checkbox's parent:
var active1, active2;
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
let checked = $('input.addnominee:checked');
active1 = $(checked[0]).parent().next('div').children('input').attr('id');
//Let's assign active2 only if we have multiple selected checkboxes:
if(checked.length > 1) active2 = $(checked[1]).parent().next('div').children('input').attr('id');
});
Here's example with click. To simplify it a bit, I added stepper class into every number input, and we're now detecting click for the class stepper:
$(document).on('click','.stepper',function(){
if($(this).attr('id') == active1){ //Check which one user clicked
if(active2 != undefined){ //Make the math only if we have another active element
var share1 = $('#'+active1).val();
var answer = 100 - share1;
$('#'+active2).val(answer);
}
}else if($(this).attr('id') == active2){
if(active1 != undefined){
var share2 = $('#'+active2).val();
var answer = 100 - share2;
$('#'+active1).val(answer);
}
}
});
Fiddle: https://jsfiddle.net/xpvt214o/677733/
This surely works also with focusout, but you need to remember that clicking stepper wont focus the input, so it wouldn't be very functional.
And with this same idea you could also disable the inputs which are not 'active'.
I hope this helps!
EDIT:
Maybe a bit simplified version with the same idea:
jQuery(document).ready(function($) {
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$(document).on('click','.stepper',function(){
var checked = $('input.addnominee:checked');
if(checked.length > 1){
var active1 = $(checked[0]).parent().next('div').children('input');
var active2 = $(checked[1]).parent().next('div').children('input');
var share = $(this).val();
var answer = 100 - share;
if($(this).attr('id') == $(active1).attr('id')){
$(active2).val(answer);
}else if($(this).attr('id') == $(active2).attr('id')){
$(active1).val(answer);
}
}
});
});
Fiddle: https://jsfiddle.net/128uzmj3/
im currently looking for help in this matter.
The problem here is that instead of doing the checkbox value + the previous value it is adding it all together like placing "10" and after other checkbox click it adds the value to it and does not count it like "1020" instead of doing 10+20
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
input.value += input.value + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Check if repeatedly click on checkbox should be handled also on uncheck score should reduced.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
total = parseInt(document.getElementById("valor").value);
if(isNaN(total)){
total = 0;
}
if($(this).prop('checked')){
total = total + parseInt($(this).val());
} else {
total = total - parseInt($(this).val());
};
var input = document.getElementById("valor");
input.value = total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
The code
input.value += input.value + total;
means (since input.value is a String), concatenate input.value with total after making sure total is a String. Don't use the += and be sure to use parseInt() on anything that you want to be a number.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
/*
* You don't need +=
* You do need to parseInt
* You need to make sure to handle empty String ""
*/
input.value = (parseInt(input.value, 10) || 0) + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label>
<br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
Please correct me, if I don't quite understand your problem, but shouldn't you just have to change input.value += input.value + total; to input.value = total; for the required result?
As you are using jQuery and I love to user reduce method I can advice you this solution
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = $('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
return pre + parseInt($(post).val());
}, 0);
$('#valor').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
If your value is always a number you can use value / 1 to convert number string into numeric type. This only if you are SURE that the number will be always a number and not a string containing number, eg. 11.jpg is not valid.
This is a performance test for your case:
https://jsperf.com/parseint-versus-divide-by-one/1
So you can rewrite the code as:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total =
$('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
var val = $(post).val() / 1;
return pre + (val ? val : 0);
}, 0);
$('#valor').val(total);
});
});
Here is the code:
<form class="ui form attached fluid loading segment" onsubmit="return contact(this)">
<div class="field">
<label>Preferred Tour</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select required id="tourInfo">';
echo '<option value="" selected disabled>--Preferred Tour--</option>';
$db = mysqli_query($conn, "SELECT `id`,`tourprice`,`tourname` FROM `available_tours`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['id']." id=".$d['tourname']. " data-price=".$d['tourprice'].">".$d['tourname']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="field" id="hiddenTortu" style="display: none;">
<label>Attention</label>
<div class="ui icon">
<p><b>The minimum of people for this tour is 5, less than 5 the tour is not realisable</b></p>
</div>
</div>
<div class="field">
<label>Available Time</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select name="gender" required id="timeInfo">';
echo '<option value="" selected disabled>--Preferred Time--</option>';
$db = mysqli_query($conn, "SELECT `time_real` FROM `available_time`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['time_real'].">".$d['time_real']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="two fields">
<div class="field" id="pax">
<label>Please specify the number of People according to the perred tour selection</label>
Here starts the problem with the following script according to the tour selection I'm trying to set up a minimum and maximum so that the user can't choose more numbers for the people on the tour.
The problem is that when the user select first one option, and then realised that the best option is another one, when he/she does another selection the input created with jQuery that was appended remains and because of the new selection a new input is created.
The intention is that if the user chooses option 1 the input append appears according to option one, but if the user regrets and prefers option 2 that the input for the option 1 disappears and a new input according to option 2 appears and so on for the entire if conditions.
<script>
$(document).ready(function(){
$('#tourInfo').on('change', function() {
if ( this.value == '1')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="1" max="2" value="1" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '2')
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="3" max="5" value="3" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '3')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="6" max="15" value="6" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}...
...});
};
})(jQuery);
$('#peopleInfo').restrict();
}
});
});
</script>
</div>
<div class="field">
<label><br>Date of Tour</label>
<input type="text" readonly required id="tourDate" class="datepicker-here form-control" placeholder="ex. August 03, 1998">
</div>
</div>
<div style="text-align:center">
<div>
<label>Ensure all details have been filled correctly</label>
</div>
<button class="ui green submit button">Submit Details</button>
</div>
</form>
</div>
Move your script out from inside the div with id pax, then
Clear your html of the element with id pax before appending:
//Using JQuery
$('#pax').html('');
Basically, what I want to do here is to keep the value in an input element a non-zero digit (0<x<=9). Here is my tag:
<input type="number" class="cell">
I have tried several JavaScript ideas, but none of them seem to work. I am using jQuery 3.2.1, BTW.
Here is what you are looking for:
<input type="number" class="cell" min="0" max="9" pattern="\d{0,9}">
Take a look at this example.
$('input[type=number]').keyup(function(e) {
var key = e.key
if (/[0-9]/.test(key)) {
e.target.value = key
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell" min="0" max="9" value="0">
There you go:
$('input[type="number"]').on('keyup click', function(){
if($(this).val() > 9){
$(this).val(9);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell">
You may use input event:
$('[type=number]').on('input', function(e) {
if (this.value > 9) {
this.value = this.value.split('').pop();
}
if (this.value <= 0) {
this.value = 1;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="cell">
To allow a number from 1 to 9, all you have to do is disallow anything with more than two numbers, i.e. a lenght over 1.
To disallow zero, prevent the default action when a zero is pressed
$('.cell').on('keydown', function(e) {
this.value = this.value.slice(1);
if (e.which === 48 || e.which === 96) e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell">
Here you go with the solution https://jsfiddle.net/pj0L78sm/3/
$('input[type="number"]').attr({
max: 10,
min: 0
});
$('input[type="number"]').keydown(function(e){
var value = $(this).val() + (parseInt(String.fromCharCode(e.which)) || 0);
if(e.which != 8 && (parseInt(value) < 0 || parseInt(value) > 10) || e.which === 189){
e.preventDefault();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell">
I have kept limit as 0 to 10 and also used jQuery 3.2.1 in jsFiddle.