JQuery/JS Input Iteration - javascript

I am getting incorrect results from my logic and I'm not sure why. Any recommendations would be highly appreciated.
I have dynamically created cards with 1-3 inputs per card. I am trying to iterate through the cards and collect the input values for each individual card but instead I keep getting the input values for all the cards for each iteration
html
<div class="card">
<input type="hidden" class="sample" value="A">
<input type="hidden" class="sample" value="B">
</div>
<div class="card">
<input type="hidden" class="sample" value="A">
</div>
js
arr = []
$('.card').each(function (i, obj) {
$('.sample').each (function (i, obj) {
val = $(this).val()
arr.push(val)
})
})
I was expecting arr[A, B] and arr[A]
but i get arr[A, B, A] and arr[A, B, A]

You are getting this result due to inner loop is executing for all samples div present into HTML.
Use $(obj).find('.sample') instead of $('.sample'). It will execute for sample div within card div.
var arr = []
$('.card').each(function (i, obj) {
var ele = [];
$(obj).find('.sample').each (function (i, obj) {
val = $(this).val()
ele.push(val)
})
arr.push(ele)
})
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<input type="hidden" class="sample" value="A">
<input type="hidden" class="sample" value="B">
</div>
<div class="card">
<input type="hidden" class="sample" value="A">
</div>

The result you are getting is expected.
There are many ways to achieve what you want: "I was expecting arr[A, B] and arr[A]"
But for me, I would go for adding more distinctions in your classes:
card-0, card-1, and so on should be coded by you
html
<div class="card-0 cards">
<input type="hidden" class="sample" value="A">
<input type="hidden" class="sample" value="B">
</div>
<div class="card-1 cards">
<input type="hidden" class="sample" value="A">
</div>
js
var mainArray = [];
var cardsCount = $('.cards').length;
for (var i1 = 0; i1 < cardsCount; i1++) {
var arr = [];
$(".card-" + i1 + " :input").each(
function() {
arr.push($(this).val());
}
);
mainArray.push(arr);
}
alert(mainArray[0]);
alert(mainArray[1]);

Related

How to remove static array after uncheck checkbox in jquery

I have two checkboxes, and I want whenever I click on any checkbox then their values (static array) should be inserted into "final" array (empty array). If I uncheck that checkbox then its value (static array) should be remove from "final array".
Right now I am inserting/pushing "static" array into blank array (final array), but I want to know that how can I remove this "static" array after uncheck checkbox ?
var myarray = [];
var model = ["Height", "size", "bust"];
var Hostess = ["Height", "bust"];
$("input:checkbox.country").click(function() {
var value = $(this).val();
if (!$(this).is(":checked"))
alert('you are unchecked ' + $(this).val());
else
myarray.push(model);
});
console.log('Final array is ', myarray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="country" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="Hostess" class="country" name="interest" value="Hostess">
<label for="hostess">Hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>
As noted in the comments, you can rebuild the array each time.
Assuming you want a 1-dimensional array rather than an array of arrays, you can use
myarray.push(...modelarray);
to add the array items.
I've used a switch here to match the checkbox value with the array variable, but a better solution for this part (already provided in another answer) is to use an object and get the array by key. I've kept this with the switch to show the difference and use of .push(...array)
var myarray = [];
var modelarray = ["A", "B", "C"];
var hostessarray = ["X", "Y"];
$("input:checkbox.country").click(function() {
// rebuild myarray
myarray = [];
$("input:checkbox.country:checked").each(function() {
switch ($(this).val())
{
case "model":
myarray.push(...modelarray);
break;
case "hostess":
myarray.push(...hostessarray);
break;
}
});
console.log('Updated array is ', myarray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="country" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="hostess" class="country" name="interest" value="hostess">
<label for="hostess">hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>
Also in fiddle: https://jsfiddle.net/cwbvqmp4/
You need to generate the array from the checked boxes each time
I suggest an object, where you can get the values based on key
I renamed the class (country) - it does not match the actual values (attributes based on interest)
let myArray;
let interests = {
"model": ["Height", "size", "bust"],
"hostess": ["Height", "bust"]
}
$("input:checkbox.interest").on("click", function() {
myArray = $("input:checkbox.interest:checked")
.map(function() { console.log(this.value,interests[this.value])
return interests[this.value]
}) // get checked boxes and their interests
.get() // return an array
.filter(val => val); // remove empty slots
console.log('Final array is ', myArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="interest" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="Hostess" class="interest" name="interest" value="hostess">
<label for="hostess">Hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>
Use conditions like below while you have static array for both checkboxes.
var myarray = [];
var model = ["Height", "size", "bust"];
var Hostess = ["Height", "bust"];
$("input:checkbox.country").click(function() {
var value = $(this).val();
if(value === "model"){
if (!$(this).is(":checked")){
myarray.splice(myarray.indexOf(model), 1);
}
else{
myarray.push(model);
}
}
else if(value === "Hostess"){
if (!$(this).is(":checked")){
myarray.splice(myarray.indexOf(Hostess), 1);
}
else{
myarray.push(Hostess);
}
}
console.log('Final array is ', myarray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="country" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="Hostess" class="country" name="interest" value="Hostess">
<label for="hostess">Hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>

Checkbox arrays

Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>

How to check multiple checkboxes with JavaScript?

I have multiple checkboxes
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
</div>
How to find all checked checkboxes and create json or array with result of checking?
In case you just want to use pure/vanilla JS, here is an example:
HTML HEAD
<script type="text/javascript">
function getCheckedCheckboxesFor(checkboxName) {
var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
return values;
}
</script>
HTML BODY
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
<input type="button" onclick="alert(getCheckedCheckboxesFor('employee'));" value="Get Values" />
</div>
JS Fiddle link: http://jsfiddle.net/dY372/
Try this:
Fiddle
jQuery:
var selected = [];
$('.data input:checked').each(function() {
selected.push($(this).val());
});
Javascript:
var checkboxes = document.getElementsByName('employee');
var selected = [];
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
selected.push(checkboxes[i].value);
}
}
Using querySelectorAll:
var checked = document.querySelectorAll('[name="employee"]:checked');
Support: IE9+.
var elements=document.getElementsByName('employee');
should return you an array of the elements you require
DEMO
function checked(){
var items=getElementsByname('checkbox');
var selectedlist=[];
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedlist+=items[i].value+"\n";
}
alert(selectedlist);
}

Show all divs on Unchecking the checkboxes

I have a code for product list in different divs based on different data attributes like data-brand,data-store and some more. I am filtering the records with checkbox selection which my friend helped me to develop.I need small change in this.Look at the code.
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div>
<div class="content"
data-category="shoes"
data-price="4000"
data-size="38"
data-brand="Nike">
<img src="http://placehold.it/120x80">
<p>Nike 38<br>$4000</p>
</div>
<div class="content"
data-category="shirts"
data-price="6000"
data-size="20"
data-brand="Nike">
<img src="http://placehold.it/140x80">
<p>Nike 20<br>$6000</p>
</div>
<div class="content"
data-category="shoes"
data-price="500"
data-size="20"
data-brand="Andrew">
<img src="http://placehold.it/120x80">
<p>Andrew 20<br>$500</p>
</div>
<div class="content"
data-category="shoes"
data-price="780"
data-size="42"
data-brand="Andrew">
<img src="http://placehold.it/120x80">
<p>Andrew 42<br>$780</p>
</div>
<div class="content"
data-category="shirts"
data-price="1200"
data-size="40"
data-brand="Sunbaby">
<img src="http://placehold.it/140x80">
<p>Sunbaby 40<br>$1200</p>
</div>
<div class="content"
data-category="shoes"
data-price="2000"
data-size="70"
data-brand="Andrew">
<img src="http://placehold.it/120x80">
<p>Andrew 70<br>$2000</p>
</div>
<div class="content"
data-category="shoes"
data-price="800"
data-size="50"
data-brand="Sunbaby">
<img src="http://placehold.it/120x80">
<p>Sunbaby 50<br>$800</p>
</div>
<div class="content"
data-category="shirts"
data-price="1300"
data-size="20"
data-brand="Nike">
<img src="http://placehold.it/140x80">
<p>Nike 20<br>$1300</p>
</div>
<div class="content"
data-category="shirts"
data-price="800"
data-size="35"
data-brand="Andrew">
<img src="http://placehold.it/140x80">
<p>Andrew 35<br>$800</p>
</div>
</div>
<form id="filter">
<div>
<input type="checkbox"
name="brand"
value="Andrew" checked>
Andrew
</input>
<input type="checkbox"
name="brand"
value="Sunbaby">
Sunbaby
</input>
<input type="checkbox"
name="brand"
value="Nike">
Nike
</input>
</div>
<div>
<input type="checkbox"
name="category"
value="shoes" checked>
Shoes
</input>
<input type="checkbox"
name="category"
value="shirts">
Shirts
</input>
</div>
<div>
<input type="radio"
name="price"
value="0-9000"
checked>
All
</input>
<input type="radio"
name="price"
value="0-999">
$0-$1000
</input>
<input type="radio"
name="price"
value="1000-2000">
$1000-$2000
</input>
<div>
<div>
<input type="radio"
name="size"
value="0-80"
checked>
All
</input>
<input type="radio"
name="size"
value="0-25">
Small
</input>
<input type="radio"
name="size"
value="26-45">
Medium
</input>
<input type="radio"
name="size"
value="46-80">
Big
</input>
<div>
</form>
</body>
</html>
css
.hidden {display: none;}
.content {border-radius: 5px; border: 1px solid #bbb;padding: 5px; margin: 5px; float: left;}
#filter {clear: left;}
script
var filterContentForm = function(content, form){
var filter = function() {
var checkBoxGroups = {},
radioGroups = {};
var addRadioGroup = function(name){
radioGroups[name] = {
el: $('input[name='+name+']:checked')
};
var n = radioGroups[name];
n.el
.each(function(){
n.range = $(this).val().split('-');
n.from = Number(n.range[0]);
n.to = Number(n.range[1]);
});
};
$('#filter input[type=radio]')
.each(function(){
addRadioGroup($(this).attr('name'));
});
var addCheckBoxGroup = function(name){
checkBoxGroups[name] = {
el: $('input[name='+name+']:checked'),
ch: []
};
var n = checkBoxGroups[name];
n.el.each(function(){
n.ch.push($(this).val());
});
};
$('#filter input[type=checkbox]')
.each(function(){
addCheckBoxGroup($(this).attr('name'));
});
var contents = $(content), all = 0;
contents.removeClass('hidden')
.each(function(){
var $this = $(this),
price = $this.data('price');
for(var c in radioGroups){
var n = radioGroups[c],
d = Number($this.data(c));
if(d < n.from || d > n.to){
$this.addClass('hidden');
all++;
return;
}
}
var show = 0, i;
for(var c in checkBoxGroups){
var n = checkBoxGroups[c],
d = $this.data(c);
for(i = 0; i < n.ch.length; i++){
if(d === n.ch[i]) {
show++; break;
}
}
}
var l = Object.keys(checkBoxGroups).length;
if(show < l) {
$this.addClass('hidden');
all++;
}
});
if(all > contents.length - 1)
contents.removeClass('hidden');
};
$(form+' input').change(filter);
filter();
};
filterContentForm('.content', '#filter');
#filter {clear: left;}
The above code is working fine.I just need one small change in this. That is, on start two checkboxes are checked i.e.for brand i.e.Nike and category i.e. shoes. I just want that on the start, these two checkboxes also need to be unchecked,all records visible,but when I am removing the 'checked' from Andrew and Shoes checkbox,Filtering doesnot happen.
Just guide me how to keep all checkboxes unchecked on start and then filtering should work after selecting the checkboxes.
Thanks for help
Your filter code seems to be a little buggy.
Make sure you are adding the jquery js in the header!
To toggle checked/unchecked state of your checkboxes and/or radio-buttons simply add/remove the checked attribute from the tag
<input type="checkbox"
name="category"
value="shoes" **checked**>
Ok so this is the problem:
You are checking the following condition
if(show < l)
where show is the count of filterCategories [ in your case: brand and category] that are checked. This is being compared against l which is count of total filterCategories present.
So, when only one of the categories is checked, this conditions becomes true, and following code
`$this.addClass('hidden');
all++;`
gets executed. This makes your all++ reach the value of contents.length hence your following code gets executed
if(all > contents.length - 1)
contents.removeClass('hidden');
which overrides the filters and shows all the items [ in your case the divs ]
To fix this see the following code. The activeFilterCount variable is the change that is required. Just replace your code from var show=0,i; to all++;} with the following code:
var show = 0, i, activeFilterCount=0;
for(var c in checkBoxGroups){
var n = checkBoxGroups[c],
d = $this.data(c);
if(n.ch.length > 0){
activeFilterCount++;
}
for(i = 0; i < n.ch.length; i++){
if(d === n.ch[i]) {
show++; break;
}
}
}
if(show < activeFilterCount) {
$this.addClass('hidden');
all++;
}
I know it got a little too lengthy, but I hope it helps you! Let me know if anything is not clear.

Sum Checked CheckBoxes Values

I'm using play framework and jquery mobile and trying to sum custom tag values of checked checkboxes but i couldn't manage this. Here is some code;
<form action="#{Waiter.payAServing()}" method="POST">
<div class="boxes">
#{list items:servs, as:'serving'}
<fieldset data-role="fieldcontain">
<div class="ui-block-a">
<input onclick="MySum()" type="checkbox" name="item" id="checkbox-${serving_index}" value="${serving.id}" to="${serving.item.price*serving.amount}" />
<label for="checkbox-${serving_index}">${serving.item.title} </label>
</div>
<div class="ui-block-b"><h2><center> ${serving.item.price*serving.amount} TL </center></h2></div>
<div class="ui-block-c"><h2> ${serving.amount} </h2></div>
</fieldset>
#{/list}
</div>
<input type="hidden" name="rid" id="rid" value="${rID}" /><br />
<input type="submit" value="Pay!" />
</form>
<div class="result"></div>
<script type="text/javascript" charset="${_reponse_encoding}">
function MySum() {
alert(0);
var selectedCustomValue = document.getElementById("checkbox-1").getAttribute("to");
var sum = 0;
alert(selectedCustomValue);
}
</script>
How can i sum to values of checked check boxes with jquery or pure javascript?
Try this:
jQuery version:
function MySum(){
var totalSum = 0;
$("input:checked[name='item']").each(function(index, el){
totalSum += parseFloat(el.value);
});
return totalSum;
}
Also to bind the click handler to checkboxes use this instead on the inline style:
$(function(){
$("[name='item']").click(MySum);
});
To get the sum of to attribute, try this:
function MySum(){
var totalSum = 0;
$("input:checked[name='item']").each(function(index, el){
totalSum += parseFloat($(el).attr("to"));
});
return totalSum;
}
A better approach would be to use data-* attributes in your markup like:
<input type="checkbox"
name="item"
id="checkbox-${serving_index}"
value="${serving.id}"
data-to="${serving.item.price*serving.amount}" />
and the MySum function would be:
function MySum(){
var totalSum = 0;
$("input:checked[name='item']").each(function(a, b){
totalSum += parseFloat($(b).data("to"));
});
return totalSum;
}

Categories

Resources