user982124 user982124 - 1 month ago 5
HTML Question

HTML Table - Track Selections for Form Submission

I've created a simple table using Bootstrap and PHP which looks like this:



<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Name</th>
<th scope="col">Date</th>
<th scope="col">Select</th>
</thead>
<tbody>

<tr id="RFIT1000">
<td>Penny Lane</td>
<td>10/03/2015</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>&nbsp;
<button type="button" class="btn btn-danger btn-sm">No</button>
</td>
</tr>
<tr id="RFIT1001">
<td>Fred Kruger</td>
<td>18/01/2016</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>&nbsp;
<button type="button" class="btn btn-danger btn-sm">No</button>
</td>
</tr>
<tr id="RFIT1002">
<td>Bob Hope</td>
<td>09/08/2016</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>&nbsp;
<button type="button" class="btn btn-danger btn-sm">No</button>
</td>
</tr>
</tbody>
</table>





This is part of a form that will be submitted and I need to track which rows were selected Yes and which rows were selected No. I would also like to add a .success class to the table row when Yes is clicked (and remove a .danger class if previously present), and when No is clicked add a . danger class to the table row (and remove a . success class if previously present).

If the user clicks Yes I would like to track the id value for the Row in a variable/array somehow and the same for the No selections. If the user changes a selection it should also remove the value from the original variable/array - e.g. if they first clicked No and then they click Yes it should add the value to the 'Yes' variable/array list and remove it from the 'No" variable/array list.

I'm still learning HTML, Javascript and CSS as I'm going so not sure what the best approach here is and how to implement a system that tracks selections and makes those available as POST values to include in the form submission?

Answer

Try using this

var store={};
//store all values of succes fauilure in an object coresponding to the id 
$("[id^=RFIT]").each(function(e,i){store[i.id]=$(i).hasClass('success')?'success':'danger'});


//on click update the closest tr class and store
$('button').click(function(){
    if($(this).hasClass('btn-success')){
        result='success';
    }else{
        result='danger';
    }
    $(this).closest('tr').attr('class',result);
   store[ $(this).closest('tr').attr('id')]=result;
});
Comments