Getting all selected checkboxes in an array
Formatted :
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Hopefully, it will work.
Getting all selected checkboxes in an array to POST to API
prepended EDIT
It looks like the OP already has access to a FormData
instance which in the OP's example code gets referred to as urlencoded
.
Thus in order to provide a quick fix for the OP's code, a solution might look like this ...
// make an array from the ...
Array.from(
// ... node list of every checked
// ckeckbox control withing the #myDiv element ...
document.querySelectorAll('#myDiv [type="checkbox"]:checked')
)
.reduce((formData, control) => {
// ... and append key/name and value to `formData` ...
formData.append(control.name, control.value);
return formData;
// ... which is represented by the `urlencoded` object
// that got provided as the `reduce` task's initial value.
}, urlencoded);
Further below one finds a fully-fledged and working example code in order to study the use of XHR
and FormData
.
+++ edit end +++
In addition to the logging check your DevTools
Network
tab as well. One should be able to inspect a failed (404) POST
request to https://stacksnippets.net/
but with the correctly sent form data.
The provided approach uses a form element where it intercepts and prevents the browser's form submit but creates an own XHR from the form's method
and action
values.
In order to collect/aggregate the form data it uses the FormData
Web API. Such an object can be directly passed to the XHR's send
method.
function createXHRFromForm(form) {
const xhr = new XMLHttpRequest;
xhr.open(
form.method,
form.action,
true
);
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
// xhr.onreadystatechange = function() {
// if (
// (this.readyState === XMLHttpRequest.DONE)
// && (this.status === 200)
// ) {
// // handle success
// }
// };
return xhr;
}
function createCheckboxFormData(form) {
// for the given example form
// following line already was sufficient enough
//
// return new FormData(form);
//
// but a custom aggregation is supposed to be shown.
return Array
.from(
form.querySelectorAll('[type="checkbox"]:checked')
)
.reduce((formData, control) => {
formData.append(control.name, control.value);
return formData;
}, new FormData);
}
function handleCheckboxDataSubmit(evt) {
evt.preventDefault();
const form = evt.currentTarget;
const xhr = createXHRFromForm(form);
const formData = createCheckboxFormData(form);
console.clear();
console.log({
entries: [...formData.entries()],
name: formData.getAll('name'),
});
xhr.send(formData);
return false;
}
function main() {
document
.querySelector('form[name="myForm"]')
.addEventListener('submit', handleCheckboxDataSubmit);
}
main();
:not([type="submit"]) {
margin: 0!important;
padding: 0!important;
}
body { zoom: .85; }
label { display: block; cursor: pointer; }
[type="submit"] { margin-top: 3px; }
<form name="myForm" action="/" method="post">
<label>
<input type="checkbox" name="name" value="1" checked/>
<span class="label">Food Deals</span>
</label>
<label>
<input type="checkbox" name="name" value="2" checked/>
<span class="label">Groceries Deals</span>
</label>
<label>
<input type="checkbox" name="name" value="3"/>
<span class="label">Karam Box</span>
</label>
<button type="submit">POST</button>
</form>
How to make an array of items which are checked in checkbox
For a plain javascript solution, you can use document.querySelectorAll()
.
Retrieve the checkboxes and then loop over them, then push()
all of the ones that have the checked: true
property to an array called checked
.
var checkboxes = document.querySelectorAll("input[type=checkbox]");var submit = document.getElementById("submit");
function getChecked() { var checked = [];
for (var i = 0; i < checkboxes.length; i++) { var checkbox = checkboxes[i]; if (checkbox.checked) checked.push(checkbox.value); }
return checked;}
submit.addEventListener("click", function() { var checked = getChecked(); console.log(checked);});
<input type="checkbox" value="first" checked><input type="checkbox" value="second" checked><input type="checkbox" value="third" checked>
<input type="submit" id="submit">
Best way to get all selected checkboxes VALUES in jQuery
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
Get value checkbox and push in array
First, you are using the wrong selector. You should change .form-check
in the javascript to .form-check-input
or .delete-checkbox
. Also you can easily get values of the selected checkboxes using jquery's .map()
method.
Change your javascript code to something like this
function multiple_delete(id) {
const selected = $(".delete-checkbox:checked").map((i, el) => el.value).get();
if (selected.length > 0) {
$.ajax({
url: "multiple-delete",
type: "POST",
data: selected.join(","),
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
How to get all the value of checked checkboxes using jquery/javascript?
You can simply use jQuery's .map()
and .get()
on all the checked check boxes:
$("label > span:contains('OTHERS')").prev().prop('checked', false);
var valor = $('input[type=checkbox]:checked').map(function(){ return this.value; }).get();console.log(valor);
$("label > span:contains('OTHERS')").prev().change(function(){ if(!this.checked) alert('Others unchecked');});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="form-group" id="documents"> <label> <input id="check_id3" type="checkbox" value="3" class="chk3" checked=""> <span>OTHERS</span> <br> </label> <div style="padding-bottom:5px"></div> <label> <input id="check_id1" type="checkbox" value="1" class="chk1" checked=""> <span>Invoice</span> <br> </label> <div style="padding-bottom:5px"></div> <label> <input id="check_id2" type="checkbox" value="2" class="chk2" checked=""> <span>Packing List</span> <br> </label> <div style="padding-bottom:5px"></div></div>
get array of checkboxes checked, and only if seletced in a specific order, then go to URL
As you didn't share code , I will not help you fix it. I can give you some hints and you can try to implement that.
Call
onClick
function on each checkbox selection.Create an
array
and push the selected checkbox's values into it.// example: checkedArr = [1,2,3,4];
maintain a final order of values with another array
// expectedArr = [1,2,3,4];
Deep compare those 2 arrays and depending on their result, proceed with your business logic.
Comparing two array with their ordervar is_same_arr = (checkedArr.length == expectedArr.length) && checkedArr.every(function(element, index) {
return element === expectedArr[index];
});
jQuery get values of checked checkboxes into array
Call .get()
at the very end to turn the resulting jQuery object into a true array.
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
console.log(searchIDs);
});
Per the documentation:
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
Related Topics
Why Do We Need to Install Gulp Globally and Locally
Search Recursively for Value in Object by Property Name
Jqgrid - Maintain Check Box Selection State - Page Refresh/Redirect/Reload
Math Random Number Without Repeating a Previous Number
Safe Evaluation of Arithmetic Expressions in JavaScript
How to Iterate (Keys, Values) in JavaScript
Validate That a String Is a Positive Integer
Boolean Variable Returns as String from JavaScript Function
Why Use Object.Prototype.Hasownproperty.Call(Myobj, Prop) Instead of Myobj.Hasownproperty(Prop)
How to Print a Stack Trace in Node.Js
How to Get the Difference of Two Dates in Mm-Dd-Hh Format in JavaScript
How to Calculate 3D Rotation on X and Y Axis from a 4X4 Matrix
Deep Copy in Es6 Using the Spread Syntax
Sum of Array Object Property Values in New Array of Objects in JavaScript