How to get multiple checkboxes values using id - javascript

I have a list of check boxes with different values.
<input type="checkbox" value="55" id="myId">
<input type="checkbox" value="65" id="myId">
<input type="checkbox" value="75" id="myId">
<input type="checkbox" value="85" id="myId">
<input type="checkbox" value="95" id="myId">
When I'm getting those values using js that will take only value=55 only. It is due to the same id="myId"
var x = "";
$("input[type='checkbox']").change(fucntion(){
if(this.checked){
x = x+","+x;
}
});
When run that will load only 55 values like-: 55,55,55,55

Attribute id should be unique. You can use an array instead of string variable. Then simply add or remove item based on the check box status:
var x = [];
$("input[type='checkbox']").change(function(){
if(this.checked){
x.push(this.value);
}
else {
var index = x.indexOf(this.value);
x.splice(index, 1);
}
console.log(x.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" id="">55
<input type="checkbox" value="65" id="">65
<input type="checkbox" value="75" id="">75
<input type="checkbox" value="85" id="">85
<input type="checkbox" value="95" id="">95

First of all don't use multiple same ids on your page, id should be unique on entire page, try data attributes instead
$("input[type='checkbox']").change(function(){
var x = "";
$("[data-id=myId]").each(function(){
if(this.checked){
x = x + $(this).val() + ",";
}
});
console.log(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" data-id="myId">
<input type="checkbox" value="65" data-id="myId">
<input type="checkbox" value="75" data-id="myId">
<input type="checkbox" value="85" data-id="myId">
<input type="checkbox" value="95" data-id="myId">

If selection order isn't important can map() the checked values to new array every change
Your string concatenation approach doesn't take into account unchecking a previously checked input
$(':checkbox').change(function(){
var vals = $(':checkbox:checked').map(function(){
return this.value
}).get()
console.log(vals.join())
})
// insert values as text for demo
.wrap(function(){
return $('<label>',{text:this.value})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="55" >
<input type="checkbox" value="65" >
<input type="checkbox" value="75">
<input type="checkbox" value="85" >
<input type="checkbox" value="95" >
Note that ID's must be unique in a page

Related

How to check all checkbox when check on one checkbox and click on a button and get the values?

for single id i did like this but how to get all id on click of button when check the universal checkbox for all the columns
My Html File:-
<td><input type="checkbox" name="option" value="{{item.customerid}} " required ></td>
<input type="button" value="Transfer" (click)="getclickedevent($event)">
My Javascript file:-
getclickedevent(event) {
let id = $("input:checkbox[name=option]:checked").val();
console.log("The Required checkbox checked is "+ id)
}
make all the id's children of one master id
then use this
var div = // getElementById, etc
var children = div.childNodes;
var elements = [];
for (var i=0; i<div.childNodes.length; i++) {
var child = div.childNodes[i];
if (child.nodeType == 1) {
elements.push(child)
}
}
I hope you don't mind but I took the approach of refactoring your code.
Here is the HTML:
<td>
<input type="checkbox" name="option" value="{{item.customerid}}" required >
</td>
<input type="button" value="Transfer">
<div id='options'>
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
</div>
And here is the jQuery. I used jQuery because you missed native javascript and jQuery in your code:
$('input[type="button"][value="Transfer"]').click( function() {
let id = $("input:checkbox[name=option]").is(':checked');
$('input[name="options"]').each(function() {
this.checked = id;
});
});
You can see it all working here.
You can get all checked checkboxes values inside button click event handler using jquery .map() method like:
var ids = $("input:checkbox[name=option]:checked").map(function(){
return $(this).val();
}).get();
console.log(ids) //==> ['xxx', 'xxx', 'xxx', ...]
This will give a basic array containing all checked checkboxes values.
DEMO:
$("#checkAll").click(function() {
$("input:checkbox[name=option]").prop('checked', this.checked);
var ids = $("input:checkbox[name=option]:checked").map(function() {
return $(this).val();
}).get();
console.log(ids)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkAll">Check All
<hr />
<input type="checkbox" name="option" value="1">Item 1
<input type="checkbox" name="option" value="2">Item 2
<input type="checkbox" name="option" value="3">Item3
This should work for you. ↓↓
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<input type="checkbox" onclick="$('input[name*=\'customer_store\']').prop('checked', this.checked);"/> Select / Deselect<br>
<input type="checkbox" name="customer_store[]" value="xyz"/>xyz<br>
<input type="checkbox" name="customer_store[]" value="abc"/>abc<br>
Add ID to your button inputs and call on them as selectors for .click().
Add a function to get the click on the select all button and set all inputs to checked used an added class of option for to select the input elements that are check boxes.
Define an empty array to hold your values. Run your checked values through .each() loop and assign them to the array.
Those values will now live in the options array.
$(document).ready(function() {
$('#selectall').click(function(){
$('.option').prop("checked", true);
});
$('#transfer').click(function() {
var options = [];
$.each($("input[type='checkbox']:checked"), function() {
options .push($(this).val());
});
console.log(options);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input type="button" id="transfer" value="Transfer">
<input type="button" id="selectall" value="Select All">

Dynamic way to generate a javascript array for each group of checkboxes?

I have several groups of checkboxes in a form. For each grouping of checkboxes(by name) I want to create an array and if the box is checked, add it to that particular array and if it's unchecked, remove it. I have that working like this:
var color = [];
var size = [];
$('input[name="color[]"]').change(function () {
color = $('input[name="color[]"]:checked').map(function(i) {
return $(this).val();
}).get();
console.log(color);
});
$('input[name="size[]"]').change(function () {
size = $('input[name="size[]"]:checked').map(function(i) {
return $(this).val();
}).get();
console.log(size);
});
label {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h4>Color</h4>
<label>
<input type="checkbox" name="color[]" value="red" />
Red
</label>
<label>
<input type="checkbox" name="color[]" value="green" />
Green
</label>
<label>
<input type="checkbox" name="color[]" value="blue" />
Blue
</label>
<h4>Size</h4>
<label>
<input type="checkbox" name="size[]" value="small" />
Small
</label>
<label>
<input type="checkbox" name="size[]" value="medium" />
Medium
</label>
<label>
<input type="checkbox" name="size[]" value="large" />
Large
</label>
</form>
What I'm wondering is if there's a way to do this dynamically so that instead of having a separate change function for each grouping of checkboxes(there will be many) is there a way to combine this into one change function and have it map to the correct array based on the name? Something like this:
var color = [];
var size = [];
$('input[type="checkbox"]').change(function () {
var group = $(this).attr('name');
value = $('input[name="' + group + '"]:checked').map(function(i) {
return $(this).val();
}).get();
console.log(color);
console.log(size);
});
label {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h4>Color</h4>
<label>
<input type="checkbox" name="color[]" value="red" />
Red
</label>
<label>
<input type="checkbox" name="color[]" value="green" />
Green
</label>
<label>
<input type="checkbox" name="color[]" value="blue" />
Blue
</label>
<h4>Size</h4>
<label>
<input type="checkbox" name="size[]" value="small" />
Small
</label>
<label>
<input type="checkbox" name="size[]" value="medium" />
Medium
</label>
<label>
<input type="checkbox" name="size[]" value="large" />
Large
</label>
</form>
I believe this is what you want. I've set up a codepen to demonstrate.
Tip here: Any time you want to initialise an arbitrary number of variables that you can access later in the global scope, it's usually a good idea to initialise them as properties on an object in the global scope.
const groups = {};
$('input[type="checkbox"]').on("change", function (e) {
const checkedInput = $(e.target);
const groupName = checkedInput.attr('name');
const updatedArray = $(`input[name="${groupName}"]:checked`).map(function(i) {
return $(this).val();
}).get();
groups[groupName] = updatedArray;
console.log(groups[groupName]);
});

How to add the checked input box in input text whether onload or onclick using jquery

Im getting the result now, but what I want is to Also get the checked input box and put into the input text not just only using on change event in jQuery but also on page loads. As you can see, one of the checkboxes below has been checked but not putting into the input text. Please see my code below:
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(",");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multiple">
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1" checked>1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
<div class="multiple">
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2" checked>2<br>
<input type="checkbox" value="3">3
</div>
You can do this easily like:
$(document).ready(function() {
$checks = $(":checkbox");
$checks.on('change', setResults);
function setResults() {
var string = $checks.filter(":checked").map(function(i, v) {
return this.value;
}).get().join(",");
$('#field_results').val(string);
}
setResults();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2" checked>2<br>
<input type="checkbox" value="3" checked>3
You should set values into input at first, try this:
$(document).ready(function() {
$checks = $(":checkbox");
$('#field_results').val(getCheckedValues());
$checks.on('change', function(){
$('#field_results').val(getCheckedValues());
});
});
function getCheckedValues(){
$checks = $(":checkbox");
var valuse = $checks.filter(":checked").map(function(i, v) {
return this.value;
}).get().join(",");
return valuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1" checked>1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3" checked>3<br>
<input type="checkbox" value="4">4<br>
<input type="checkbox" value="5" checked>5<br>
The easiest way to do it You can use .trigger() to set default value
$checks.trigger('change');

Jquery looping and incrementing

I have 3 input types :
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
I have a jquery script that is triggered on a click and append 3 input type like the following, the script just keeps adding the trio of inputs, as much as needed by the user:
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
There is also a delete button that deletes the 3 inputs.
I'm looking for a way that on each clicks, Jquery loops though all the checkboxes and rename the "name" attribute so it's never missing a number.
Because right now i'm having a problem that when the user deletes inputs I have some names like :
check[0], check[3]
missing :
check[1] and check [2]
So is there a way to loop on each click and reset all the names to be from 1 to number of trio inputs I have ?
Thanks
Just remove index from checkbox names. use
<input type="checkbox" name="check[]" value="randomval">
and you're OK.
DEMO
Also see
HTML multiple input with same name
HTML form input tag name element array with JavaScript
According to comment, to re-assign new index you can do something like below on after each delete and new add:
function reIndex() {
var inputs = $('input[name^=check]');
inputs.each(function (i, el) {
this.name = 'check[' + (i+1) + ']';
});
}
DEMO
Every delete you can iterate the checkboxes and renumber them. Check the DEMO below
function deleteGroup(node){
$(node).closest('.pool').remove();
var counter = 0, arrayIndex = -1, itemCount = 3;
$('#all input[type=checkbox]').each(function(){
++arrayIndex;
if((arrayIndex)%itemCount==0){++counter;}
$(this).prop('name','check['+counter+']');
})
}
function add(){
var idx = ($('#all .pool:last input[type=checkbox]').prop('name').substring(6,7))*1 + 1;
$('#all').append('<div class=pool>'
+'<input type="checkbox" name="check['+idx+']" value="randomval">'
+'<input type="checkbox" name="check['+idx+']" value="randomval">'
+'<input type="checkbox" name="check['+idx+']" value="randomval">'
+'<button onclick="deleteGroup(this)" >Remove</button>'
+'</div>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="all">
<div class=pool>
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
<input type="checkbox" name="check[0]" value="randomval">
<button onclick="deleteGroup(this)" >Remove</button>
</div>
<div class=pool>
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
<input type="checkbox" name="check[1]" value="randomval">
<button onclick="deleteGroup(this)" >Remove</button>
</div>
</div>
<button onclick="add()" >Add</button>

dynamic variable name from form input name

How would i create a dynamic variable name based on all the forms input checkbox list names? This is what i have so far
var nameArray = [];
$.each($("#store-filter input").serializeArray(), function(i, field) {
nameArray[field.name] = field.value;
});
alert(nameArray[0]);
for (i = 0; nameArray.length > i; i++)
{
//alert(nameArray[i]);
var nameArray[i] = nameArray[i].value;
var nameArray[i]+'_checked_values' = $(\'input[name="nameArray[i]+[]"]:checked\').map(function() {
return this.value;
}).get();
}
alert(make); //variable name from name="make[]"
sample HTML
<form id="store-filter" action:"javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
so later on in my code i can create a url string ?make=1,2,3&store=40,5,6&time=1,2,3,4 etc
the $_GET parameters are taken from the input check boxes name's dynamically
I'd suggest the following approach, obviously I'm binding to the click of a button, you should add that to the event/interaction of your choice:
function makeQueryString() {
function keyValues(idPref) {
// using the pass-in 'id' as a key:
var key = idPref,
// searching within the element identified with that 'id' for
// other elements whose 'id' *starts* with that string:
values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() {
// iterating over those found elements and, if the value is *not* the
// defaultValue (value on page-load), *or* the checked state is not the
// default state (checked/unchecked as on page-load):
if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) {
// we return the value:
return this.value;
}
// get() converts to a JavaScript Array, join() concatenates Array elements
// to form a string:
}).get().join(',');
// if there is a key, and there are associated values, we return a 'key=value,value2'
// string, otherwise we return an empty string:
return key && values.length ? key + '=' + values : '';
}
// we return the value obtained after iterating over the form's span elements
// that have an [id] attribute:
return $('form span[id]').map(function(){
// obtaining the 'key=value1,value2' strings from the called-function:
return keyValues(this.id);
// converting those returned elements into an Array, and joining with & characters:
}).get().join('&');
}
$('#test').click(function(e) {
e.preventDefault();
console.log(makeQueryString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test</button>
<form id="store-filter" action: "javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
References:
CSS:
Attribute-presence and value ([attribute],[attribute="value"]) selectors.
JavaScript:
Array.prototype.join().
defaultChecked and defaultValue (HTMLInputElement).
jQuery:
get().
map().
You are in Javascript, you do not need to declare the size of your arrays, there is no propblems by adding/removing anything from an Object/Array.
You should create a variable make then get the values in. Finally, you will be able to get it back.
var make;
$.each($("#store-filter input").serializeArray(), function(i, field) {
make[i] = field.name;
});
Later in your code, you will use the array make.
make[0];
EDIT:
Here is an example i did for you: http://jsfiddle.net/kjkzm8qm/
NOTE: Your $.each($("#store-filter input").serializeArray() ... is useless, you should select all your inputs by adding a class AND, you should END your input tags by adding a / at the end.
HTML
<input name="test" class="inputs" />
JAVASCRIPT
$.each($(".inputs"), function(){ });
Update for david's answer.
If you want to remove & then add this code below
For this check the key value is not null
let keyValue = keyValues(this.id);
if (keyValue != ''){
return keyValue;
}

Categories