I have a textbox that can be append.. and i want to get the values of each textbox
$('#entryData').append('<div><input type="text" id="quantity"></div>');
var total = $('#quantity').val();
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="entryData">
<input type="text" id="quantity">
<input type="button" value="+">
<input type="button" value="Total">
</div>
but I am only getting the first textbox value and not the other textbox
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id='entryData' >
<input type="text" class='quantity'>
<input type="button" value="+" id='add'>
<input type="button" value="Total" id='total'>
</div>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#entryData').append('<div><input type="text" class="quantity"></div>');
});
$('#total').click(function(){
var total=0;
$('.quantity').each(function(index,quantity){
total=total+parseInt($(this).val());
});
alert(total);
});
});
</script>
I expect this is what you are trying to do?
Or make it like this:
<div id='entryData' >
<input type="number" class='quantity'>
<input type="button" value="+" id='add'>
<input type="button" value="Total" id='total'>
</div>
If you expect numbers - make the field number.
//this should come from helper method file/lib - for reusability
const sum = (accumulator, currentValue) => accumulator + currentValue;
const mapToInt = (idx,element) => { if (element.value !== "") { return parseInt(element.value, 10); } }
$(document).ready(() =>{
$('#add').click( () => {
$('#entryData').append('<div><input type="number" class="quantity" /></div>');
});
$('#total').click( () => {
let total = $(".quantity").map(mapToInt).get().reduce(sum);
console.log ( total );
});
});
Edit: sum (aggregation func) and mapToInt can be reused if you consider having more functional approach.
Related
I have a checkbox which add an id of his value in array when checked and I want to delete this value when I uncheck it
I tried to remove my id with and indexOf() + splice() but I can't use indexOf() because I'm using an object
Some one have an idea to how can I delete my id when I uncheck my checkbox,
or if there is a trick to use indexOf with an object?
there is my script :
$(document).ready(function() {
const formInputIds = $('form#export input[name="ids"]');
$('.exportCheckbox:checkbox').on('change', function() {
const announceId = $(this).data('id');
if (this.checked) {
formInputIds.push(announceId);
console.log(formInputIds);
} else {
const index = formInputIds.val().indexOf(announceId);
if (index > -1) {
formInputIds.val().splice(index, 1);
}
console.log(formInputIds);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<some data of product displayed>
<input type="checkbox" data-id="{{annonce._id}}" class="exportCheckbox"/>
there is the console.log of formInputIds with 3 ids :
Consider the following.
$(function() {
var formInputIds;
function getChecked(target) {
var results = [];
$("input[type='checkbox']", target).each(function(i, elem) {
if ($(elem).is(":checked")) {
results.push($(elem).data("id"));
}
});
return results;
}
$('.exportCheckbox').on('change', function(event) {
formInputIds = getChecked($(this).parent());
console.log(formInputIds);
});
$("#export").submit(function(event) {
event.preventDefault();
console.log(formInputIds);
$("[name='ids']", this).val("[" + formInputIds.toString() + "]");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<div class="some content">
<input type="checkbox" data-id="1001" class="exportCheckbox" />
<input type="checkbox" data-id="1002" class="exportCheckbox" />
<input type="checkbox" data-id="1003" class="exportCheckbox" />
<input type="checkbox" data-id="1004" class="exportCheckbox" />
<input type="checkbox" data-id="1005" class="exportCheckbox" />
<input type="checkbox" data-id="1006" class="exportCheckbox" />
</div>
This way, you build the Array based on just the checked items. No need to find and slice the exact item.
let plus_btns = document.querySelectorAll('#plus-button');
let minus_btns = document.querySelectorAll('#minus-button');
let qty_inputs = document.querySelectorAll('#quantity');
plus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
qty_inputs.forEach(qty=>{
qty.value++
})
})
})
minus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
qty_inputs.forEach(qty=>{
if(qty.value > 1){
qty.value--
}
else{
qty.value=0;
}
})
})
})
<div class="cart-totals">
<input type="button" value="-" id="minus-button" for="quantity">
<input type="number" id="quantity" value="1" min="0">
<input type="button" value="+" id="plus-button" for="quantity">
<input type="button" value="-" id="minus-button" for="quantity">
<input type="number" id="quantity" value="1" min="0">
<input type="button" value="+" id="plus-button" for="quantity">
</div>
How I can change value of specific quantity input ???
In my case click event triggers all inputs and change the value of each input.
Please guide me thanks.
This should do the trick.
let plus_btns = document.querySelectorAll('#plus-button');
let minus_btns = document.querySelectorAll('#minus-button');
let qty_inputs = document.querySelectorAll('#quantity');
plus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
btn.previousElementSibling.value++;
})
})
minus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
btn.nextElementSibling.value = (btn.nextElementSibling.value == 0) ? 0 : btn.nextElementSibling.value - 1;
})
})
Use event delegation for a single generic document wide handler. Afaik for is not a valid attribute for input type 'button', so use a data-attribute. Furthermore: element id must be unique. Fixed all that in this demo snippet:
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.type === "button") {
return handleBtn(evt.target);
}
}
function handleBtn(btn) {
const elem = document.querySelector(`#${btn.dataset.for}`);
const nwValue = +elem.value + (btn.value === "-" ? -1 : 1);
elem.value = nwValue >= +elem.min ? nwValue : elem.min;
}
<div class="cart-totals">
<input type="button" value="-" data-for="quantity1">
<input type="number" id="quantity1" value="1" min="0">
<input type="button" value="+" data-for="quantity1">
<input type="button" value="-" data-for="quantity2">
<input type="number" id="quantity2" value="1" min="1">
<input type="button" value="+" data-for="quantity2">
</div>
Using a single event handler:
var cart = document.querySelector('.cart-totals');
cart.addEventListener('click', function(ev) {
var tgt = ev.target;
if (tgt.matches('input[type="button"]')) {
var input = document.getElementById(tgt.dataset.for);
var currentValue = +input.value;
var minValue = +input.min;
if (tgt.value === '+') {
input.value = currentValue + 1;
}
else if (currentValue > minValue) {
input.value = currentValue - 1;
}
}
});
<div class="cart-totals">
<input type="button" value="-" data-for="quantity1">
<input type="number" id="quantity1" value="1" min="0">
<input type="button" value="+" data-for="quantity1">
<input type="button" value="-" data-for="quantity2">
<input type="number" id="quantity2" value="5" min="2">
<input type="button" value="+" data-for="quantity2">
</div>
Two div having class name container containing same elements with same class name. Apply Jquery when that respective children are clicked.
HTML CODE
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
I have written Some scripts, which will hide negative input and display None when value is 0, positive input will increase a value
$(document).ready(function() {
var counter = 1;
if ($('.qty').val() === 0 || $('.qty').val() === '') {
$('.qty').hide();
$('.txt').show();
$('.negative').hide();
} else {
$('.txt').hide();
$('.qty').show();
$('.negative').show();
}
$('.positive').click(function() {
$('.negative').show();
$('.qty').show();
$('.txt').hide();
const qty = $('.qty').val();
$('.qty').val(counter);
counter++;
});
$('.negative').click(function() {
const qty = $('.qty').val();
if (qty > 1) {
counter--;
$('.qty').val(counter);
} else {
counter = 1;
$('.negative').hide();
$('.txt').show();
$('.qty').hide();
}
});
});
I am not sure how to use $(this) in above code.
I am beginner in JS and I know this code is not efficient.
If possible make it efficient.
Thank you!!!
I'm doing this in the code below by using .parent().find(). This can be brittle though if you rearrange your layout, so just be careful with it. You'd be better off giving a data attribute to the elements and modifying them that way.
$(document).ready(function() {
$("input").click(function() {
let clickAction = $(this).val();
console.log($(this).val());
let displayElement = $(this).parent().find("input.qty");
let currentval = +$(displayElement).val();
//you could use eval to make this look cleaner, but eval is often frowned upon
if (clickAction == "+") {
currentval++;
} else if (clickAction == "-") {
currentval--
}
$(displayElement).val(currentval);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="0">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="0">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
I have a form, i am able to calculate total of all dynamically added inputs, but i am to re-calculate after the delete row, Here is my code.
I have followed the code,
http://jsfiddle.net/Uwbe6/2/
calcSum();
function calcSum() {
var myForm = $('#myForm');
myForm.delegate('.items', 'change', function() {
var sum = 0;
var itemsValue = myForm.find('.items');
itemsValue.each(function() {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
// sum += parseInt($(this).val());
});
// return sum;
$('.total-amt').html(sum);
// console.log(sum);
});
}
$('body').on("click", ".delete", function(e) {
$(this).parent().remove();
calcSum();
});
$(function() {
var i = 1;
$('#add_more').click(function(event) {
event.preventDefault();
$('input.items').last().attr('name', 'item[' + i + ']');
$('#cart_items').append($('#tmp_cart').html());
i++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST" id="myForm">
Total Items<input type="text" value="100" name="total_amt" id="total_amt">
<div id="cart_items">
Items<input type="text" name="item[0]" class="items"><br/>
</div>
<button type="button" id="add_more">Add More</button>
<input type="submit" name="submit" value="submit">
</form>
<p>Total Amt:<span class="total-amt"></span></p>
<div id="tmp_cart" style="display: none;">
<div class="cart_items">
<label>
Items
<input type="text" name="item[]" class="items">
</label>
<input type="button" value="Delete" class="delete"><br/>
</div>
</div>
Thanks for suggestions.
calcSum() should just calculate the sum, not bind a handler. Then you can call it from different handlers.
calcSum();
function calcSum() {
var myForm = $('#myForm');
var sum = 0;
var itemsValue = myForm.find('.items');
itemsValue.each(function() {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
// sum += parseInt($(this).val());
});
// return sum;
$('.total-amt').html(sum);
// console.log(sum);
}
$("#myForm").on("change", ".items", calcSum);
$('body').on("click", ".delete", function(e) {
$(this).parent().remove();
calcSum();
});
$(function() {
var i = 1;
$('#add_more').click(function(event) {
event.preventDefault();
$('input.items').last().attr('name', 'item[' + i + ']');
$('#cart_items').append($('#tmp_cart').html());
i++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST" id="myForm">
Total Items<input type="text" value="100" name="total_amt" id="total_amt">
<div id="cart_items">
Items<input type="text" name="item[0]" class="items"><br/>
</div>
<button type="button" id="add_more">Add More</button>
<input type="submit" name="submit" value="submit">
</form>
<p>Total Amt:<span class="total-amt"></span></p>
<div id="tmp_cart" style="display: none;">
<div class="cart_items">
<label>
Items
<input type="text" name="item[]" class="items">
</label>
<input type="button" value="Delete" class="delete"><br/>
</div>
</div>
Use .on() instead of .delegate() since it's deprecated. Also, you could simply keep the event binding separate from calcSum function.
var myForm = $('#myForm');
calcSum();
function calcSum() {
var sum = 0;
var itemsValue = myForm.find('.items');
itemsValue.each(function() {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
// sum += parseInt($(this).val());
});
// return sum;
$('.total-amt').html(sum);
// console.log(sum);
}
myForm.on('change', calcSum);
$('body').on("click", '.delete', function(e) {
$(this).parent().remove();
calcSum();
});
$(function() {
var i = 1;
$('#add_more').click(function(event) {
event.preventDefault();
$('input.items').last().attr('name', 'item[' + i + ']');
$('#cart_items').append($('#tmp_cart').html());
i++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST" id="myForm">
Total Items<input type="text" value="100" name="total_amt" id="total_amt">
<div id="cart_items">
Items<input type="text" name="item[0]" class="items"><br/>
</div>
<button type="button" id="add_more">Add More</button>
<input type="submit" name="submit" value="submit">
</form>
<p>Total Amt:<span class="total-amt"></span></p>
<div id="tmp_cart" style="display: none;">
<div class="cart_items">
<label>
Items
<input type="text" name="item[]" class="items">
</label>
<input type="button" value="Delete" class="delete"><br/>
</div>
</div>
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>