set value array in all inputs with same tag class - javascript

I'm trying to do loop over all tag with same className and get their value:
var quantity = [];
$(".add_more_items").each(function(){
quantity.push($(this).val());
});
this is a result, for example:
['1', '9', '1']
but my problem is I'm trying to set value from this array to other input with same class:
$.each(quantity, function(index, val){
$(".items_final").val(val);
});
but always set in all inputs last value from my array, i donĀ“t know what I'm doing wrong.

Use an index assuming there is 1 to 1 mapping between the fields
const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
$final[i].value = item.value; // or $final.eq(i).val(item.value)
});
const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
$final[i].value = item.value; // or $final.eq(i).val(item.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Add more</h3>
<input type="text" value="1" class="add_more_items" />
<input type="text" value="2" class="add_more_items" />
<input type="text" value="3" class="add_more_items" />
<input type="text" value="4" class="add_more_items" />
<hr/>
<h3>final</h3>
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
Also this is useful:
const quantity = $(".add_more_items").map(function(){
return this.value; // or $(this).val()
}).get();

Related

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

jquery checkbox get value text input

I have list input checkbox
<input type="checkbox" name="id_image" value="homies_01" class="id_image" />
<input type="checkbox" name="id_image" value="homies_02" class="id_image" />
<input type="checkbox" name="id_image" value="homies_03" class="id_image" />
<input type="text" name="id_image" value="" class="id_image_check" />
How to check multiple input checkbox i have show value to input type="text"as
<form>
<input type="text" name="id_image" value="homies_01, homies_02, homies_03" class="id_image_check" />
</form>
There is a perfecly solution with Vanilla Javascript
function attachListeners() {
var checkboxes = document.getElementsByClassName('id_image')
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getAndPutValues, false);
}
}
function getAndPutValues() {
var result = [];
document.querySelectorAll(".id_image:checked").forEach(function(item) { result.push(item.value);});
document.querySelector('.id_image_check').value = result.join(', ');
}
attachListeners();
With jquery
$(".id_image").on("click",function(){
$(".id_image_check").val(
$(".id_image :checked").map((i,el) => el.value).join(", ")
)
});
First of all you should use array notation for checkbox names
<input type="checkbox" name="id_image[]" value="homies_01" class="id_image" />
<input type="checkbox" name="id_image[]" value="homies_02" class="id_image" />
<input type="checkbox" name="id_image[]" value="homies_03" class="id_image" />
It will help you to post multiple values simultaneously
After that for checking values in jQuery you can use
<script type="text/javascript">
$('[name="id_image[]"]').click(function(){
var value = '';
$('[name="id_image[]"]:checked').each(function(){
value += $(this).val();
});
$('#id_image_check').val(value);
});
</script>
Try this :
<input type="checkbox" name="id_image" value="homies_01" class="id_image" onchange="toggleCheckbox(this)" />
<input type="checkbox" name="id_image" value="homies_02" class="id_image" onchange="toggleCheckbox(this)" />
<input type="checkbox" name="id_image" value="homies_03" class="id_image" onchange="toggleCheckbox(this)" />
<input type="text" name="id_image" id="id_image" value="" class="id_image_check" />
<script type="text/javascript">
var arrImages = [];
function toggleCheckbox(element) {
console.log('element', element.value);
arrImages.push(element.value);
document.getElementById("id_image").value = arrImages;
}
</script>
Just use square brackets [] at end of name if you want to submit it using form or use the following method in jQuery to get values of multiple selected checkboxes.
$('#show').click(function(){
values = "";
$('input.id_image:checked').each(function(){
values += $(this).val() + " ";
});
if(values){
$('#values').html(values);
}else{
$('#values').html("None");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="id_image[]" value="homies_01" class="id_image" /> Homies 1
<input type="checkbox" name="id_image[]" value="homies_02" class="id_image" /> Homies 2
<input type="checkbox" name="id_image[]" value="homies_03" class="id_image" /> Homies 3
<br>
<button id="show">Show</button>
<br>
<div id="values"></div>

Getting all the values inside the Div

I have a div that has multiple input fields. My HTML looks like this:
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" onclick="getAllValues();" />
After I click the image, it must get all the values inside the mainDiv. How can I do this?
$("#getallvalues").click(function() {
var values = $("#mainDiv input").map(function() {
return $(this).val()
}).get().join(",");
console.log(values)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
Loop through each input then get the value and use .map()
var price = 0;
var tax = 0;
var others = 0;
$("#getallvalues").click(function() {
$("#mainDiv input").each(function() {
if ($(this).attr("id") == "price") {
price = $(this).val()
}
if ($(this).attr("id") == "tax") {
tax = $(this).val()
}
if ($(this).attr("id") == "others") {
others = $(this).val()
}
})
console.log("price " + price)
console.log("tax " + tax)
console.log("others " + others)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
You can use .map() to iterate over element and return the value in call back along with .get() to get them in array:
function getAllValues(){
$('#mainDiv input').map({
return this.value;
}).get(); // Output: ["priceval","taxval","otherval"]
}
You can use above array to create the data in whichever format(csv,json,etc) you want for further processing.
Loop through all the inputs in mainDiv
$('#mainDiv input').each(function(){
// Do what ever
})
Another way of doing this is like follows:
$('#mainDiv').find('input').each(function (index, element) {
var yourValue = element.value; // or $(element).val();
// And rest of your code
});
$('#mainDiv input').each(function(){
console.log(this.val());
})

How to get a value and label in a textbox

function radioVal(){
//var radVal = document.mainForm.rads.value;
var radVal = document.getElementsByName("rads").value;
result.innerHTML = 'You selected: '+radVal;
}
<div class="pres">
<input type="radio" id="radio01" name="rads" value="10" checked />
<label for="radio01" class="dis"><span>1 time service</span></label>
</div>
<div class="pres">
<input type="radio" id="radio02" name="rads" value="20" />
<label for="radio02" class="dis"><span>Every week</span></label>
</div>
<div class="pres">
<input type="radio" id="radio03" name="rads" value="15" />
<label for="radio03" class="dis"><span>Every 2 weeks </span></label>
</div>
<div class="pres">
<input type="radio" id="radio04" name="rads" value="10" />
<label for="radio04" class="dis"><span>Every 4 weeks</span></label>
</div>
<input type="text" value="" id="result" name="perce" />
<input type="text" value="" id="txtservV" name="servicename" />
<input type="text" value="" id="final_pay" name="final_pay" />
Hello i am using this function to get the value of a selected radio button in a textfield name perce and its value in a field name servicename any one help me in it to sourt it out. I am using this function in doucument.ready function.
Use Document.getElementsByName function which returns array of elements (or better collection, array-like object), so that you can access value of input by index (0 in your case):
var perceVal = document.getElementsByName("perce")[0].value
In case of radio buttons you have to iterate through elements and find which one is checked:
var rads = document.getElementsByName("rads");
var radsValue;
for (var i = 0; i < rads.length; i++) {
if (rads[i].checked) {
radsValue = rads[i].value // here is checked radio
break;
}
}

How to get key (index) value of a textbox in array textboxes

I want a jQuery function or javascript that alert the index and the value of array textboxes : e.g.
<input type="text" name="textbox[]" value="1" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="foo" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="banana" onblur="javascriptfunction(this.value,this.index)" />
Whenever mouse moves for example from the first input I have this alerted (1,0) and second is (foo,1) and so on. I couldn't find the function that does that. Please help.
You can use jQuery index() and val() like
$('input').blur(function(){
alert($(this).val() + ',' + ($(this).index()-1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
Update
To target certain elements or have this in a named function, first, put identifiers on your elements such as a class my-class. Then, make a named function and pass it to the jQuery blur function
$('.my-class').blur( alertIndexAndVal );
function alertIndexAndVal(){
alert($(this).val() + ',' + ($(this).index()-1));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="my-class" type="text" name="textbox[]" value="1" />
<input class="my-class" type="text" name="textbox[]" value="foo" />
<input class="my-class" type="text" name="textbox[]" value="banana" />
var textboxes = $('input[name="textbox[]"]');
textboxes.on('blur', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
I figured I'd post a javascript solution which to be honest attempts to do something like the index function of jquery although i think jquery function might be better.
var getIndexValue = function (e) {
var children = e.parentElement.children;
for (var i = 0; i < children.length; i++) {
if (children[i] == e) {
alert("Index: " + (i+1) + ", Value: " + e.value);
}
}
}
<div>
<input type="text" name="textbox[]" value="one" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="two" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="three" onblur="getIndexValue(this)">
</div>
Index: (i+1)
Value: (e.value);

Categories