Reputation: 13333
I have my markup like this. I want to get the each selected values inside an array. So that I can use them in my php ajax file.
<form id="assign-files">
<table class="send-request">
<tbody>
<tr>
<td>
<input type="checkbox" class="check" name="translation_document_id[]" value="4" >
</td>
<td>File 124</td>
</tr>
<tr>
<td>
<input type="checkbox" class="check" name="translation_document_id[]" value="5" >
</td>
<td>File New</td>
</tr>
<tr>
<td>
<input type="checkbox" class="check" name="translation_document_id[]" value="8" >
</td>
<td>New Docs</td>
</tr>
<tr>
<td>
<input type="checkbox" class="check" name="translation_document_id[]" value="28" >
</td>
<td>New Docs here</td>
</tr>
</tbody>
</table>
<button class="assign btn btn-primary pull-right">Assign Files</button>
</form>
My jquery file is like this
<script>
jQuery(document).ready(function($) {
$('body').on('click', 'button.assign', function() {
var atLeastOneIsChecked = $('input[name="translation_document_id[]"]:checked').length > 0;
if( atLeastOneIsChecked == true ) {
var ids = [];
var Selected = $(this).parents('form').find('input[type=checkbox]');
Selected.find(':checkbox:checked').each(function(i) {
var obj = {};
obj["id"]=$(this).val();
});
console.log(ids);
}
if( atLeastOneIsChecked == false ) {
alert('select at least one checkbox');
}
});
});
</script>
Here I don't get the values for the selected checkbox. How to get the selected values like an array?
Upvotes: 0
Views: 2120
Reputation: 6722
This should work :
$('body').on('click', 'button.assign', function() {
var atLeastOneIsChecked = $('input[name="translation_document_id[]"]:checked');
if( atLeastOneIsChecked.length ) {
var ids = [];
var Selected = $(this).parents('form').find('input[name="translation_document_id[]"]:checked');
Selected.each(function(pos,element) {
ids.push($(this).val());
});
console.log(ids);
} else {
alert('select at least one checkbox');
}
});
Upvotes: 2
Reputation: 82241
Let us have a look at these two lines in your code:
var Selected = $(this).parents('form').find('input[type=checkbox]');
Selected.find(':checkbox:checked').each(function(i) {
The code is finding checkbox checked element in selector. which do not exist. You should rather use filter instead of find here. also using .map()
is cleaner way to get the collection of info associated with object:
var Selected = $(this).parents('form').find(':checkbox:checked');
var selectedids = Selected.map(function(i) {
return $(this).val();
}).get();
Upvotes: 0
Reputation: 133403
Code
var ids = [];
var form = $(this).parents('form');
form.find(':checkbox:checked').each(function(i) {
var obj = {};
obj["id"] = $(this).val();
//Push to array
ids.push(obj)
});
Alternatively, .map()
can be used
var ids = $(this).parents('form').find('input[type=checkbox]:checked').map(function() {
return {
id: $(this).val()
}
}).get();
Upvotes: 1