Trying to :
- Verify if a checkbox got selected.
2.Retrieve the value. - Save a value in an array.
So my array would have the following values: [1,21,111]
What him I missing, any guidance would be appreciated.
After I’ve figured this out… will go and create another array to store the automationName.
var SelectedItems = [];
$('.btn1').on('click', function() {
SelectedItems.length = 0;
$('#flowtable tbody tr').each(function() {
// if ($(this).is(':checked')) {
// if ($('.scheduleMe').is(':checked')) {
if ($('td .scheduleMe').is(':checked')) {
SelectedItems.push($(this).attr("id"));
}
});
console.log('Checked #' + SelectedItems.length);
console.log("list 2= " + SelectedItems);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<h1>jQuery Crash Course</h1>
</header>
<div id="container">
<form id="form">
<table id="flowtable">
<tbody>
<tr class="selected">
<td id="1"></td>
<td class="automationName"> automation 1</td>
<td><input type="checkbox" class="scheduleMe" name="vehicle1"></td>
</tr>
<tr>
<td id="21"></td>
<td class="automationName">automation 21</td>
<td><input type="checkbox" class="scheduleMe" name="vehicle21"></td>
</tr>
<tr>
<td id="111"></td>
<td class="automationName">automation 111</td>
<td><input type="checkbox" class="scheduleMe" name="vehicle111"></td>
</tr>
</tbody>
</table>
<button type="button" class="btn1">check list box</button>
</form>
</div>
2
Answers
Firstly, give the checkboxes a value which is the
id
they relate to, not the the sibling/parenttd
.From there you can simplify your logic by using
map()
to build an array of the selected values only once, when the button is clicked, not having to maintain additions/deletions from the higher scoped array when a change is made.Below is a working example. Note the use of
label
elements to make the clickable area of the checkboxes bigger.If, for whatever reason, you can’t change the HTML, then you can read the value from the
td
inmap()
like this:callMe()
is a function that is handling all logic.checked
.includes()
. method.