Reputation: 341
I am trying to push the value of each check box value inside the array but every it pushes same data twice or as many checkbox i select if I choose 3 checkbox and the last check has the value of 2 so it is pushing 3 into the array 3 times and not storing the value of other two
The Jquery Code:
$('#data_table').append("<tr>"+"<td><input type='checkbox' class='checkbox' name='check' id='checked_box"+j+"' value='"+time+" 'onclick='myFunction(this)' ></td>" +"<td>"+sites.siteName +"</td>"+ "<td>" + values.deviceName + "</td>" + "<td>" + values.count + "</td>" + "<td>" + parseFloat(time).toFixed(2) + " Min" + "</td>" + "</tr>");
The Javascript Code:
var check_id=e.getAttribute('id');
var time = document.getElementById(check_id).value;
var values = [];
for(var j=0 ; j<time.length ; j++){
if(checkboxes[j].checked){
values.push(time);
}
}
console.log(values);
I just want to get the checkbox values and add it up and show the total but as i mentioned it is pushing the same data as many times i select a checkbox
Please solve this problem for me, Any help will be highly appreciable......
Upvotes: 0
Views: 59
Reputation: 2454
It's because you are pushing time
into the array, which is the value of the checked box, not the values of each checkbox individually.
You would need to change your code to set time
in the loop, instead of outside it. Then again, I'm not sure what you're trying to do with it, so I've had to make some assumptions as well as a few changes to make this work like I think you want it to.
var time = new Date().getSeconds();
var values = [{deviceName: "laptop"},
{deviceName: "desktop"},
{deviceName: "tablet"},
{deviceName: "cell"},
{deviceName: "fablet"}];
var sites = [{siteName: "StackExchange"},
{siteName: "Google"},
{siteName: "AltaVista"},
{siteName: "AskJeeves"},
{siteName: "InfoSeek"}];
for (var j = 0; j < values.length; j++)
{
$('#data_table').append("<tr>"+"<td><input type='checkbox' class='checkbox' name='check' id='checked_box"+j+"' value='"+time+" 'onclick='myFunction(this)' ></td>" +"<td>"+sites[j].siteName +"</td>"+ "<td>" + values[j].deviceName + "</td>" + "<td>" + values.count + "</td>" + "<td>" + parseFloat(time).toFixed(2) + " Min" + "</td>" + "</tr>");
}
function myFunction(e)
{
var checkboxes = $(e).closest('form').find(':checkbox');
var values = [];
for(var j=0 ; j<checkboxes.length ; j++){
if(checkboxes[j].checked){
values.push(checkboxes[j].value);
}
}
console.log(values);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<table id='data_table'></table>
</form>
Upvotes: 1