How to compute the total average of per students using Javascript - javascript

I hope my title is enough to understand my question, ive been post this question several times but I hope this time I get help from you guys.
<table id="blacklistgrid" border="2px">
<tr>
th id="th">Students Name</th>
</tr>
{% for student in teacherStudents %}
<tr class="tr2">
<td id="td">{{ student.Students_Enrollment_Records.Student_Users }}</td>
</tr>
{% endfor %}
</tr>
</table>
<button type="button" value="" class="save" onclick="doTheInsert()" title="Insert New Cell" id="save">&plus; Insert New Cell</button>
<button type="button" value="" class="save" onclick="undoTheInsert()" title="Undo Recent Action" id="unsave">× Undo Recent Action</button>
<button type="button" value="" class="save" onclick="compute()" title="Undo Recent Action" id="compute">Compute</button>
this is my script for the button Insert Cell
<script>
var counter = 0;
function doTheInsert(){
let header=$("tr#tr"); // same as $.find("tr[id='tr2']")
$('#th').after("<th data-id='headers' id='header'><input type='date'></th>");
let rows=$(".tr2");
rows.append("<td data-id='row' ><input type='number' class='average'/></td>");
counter++;
}
</script>
this is my current script in computation
<script>
function compute(){
var sum = 0;
var rows = document.getElementsByClassName("average");
for(var i = 0; i < counter; i++){
sum += parseInt(rows[i].value);
}
var average = sum / counter;
document.getElementById("demo").innerHTML = average;
let header=$("tr#tr"); // same as $.find("tr[id='tr2']")
$('#thb').before("<th data-id='headers' id='headerss'>Average</th>");
}
</script>
this is the results I get ,
it only compute the average of first students
this is the result I want
when ive tried this query from Mr #Saket Yadav
<script>
function compute(){
var sum = 0;
var rows = document.getElementsByClassName("average");
$(".average").each(function () {
sum += parseInt($(this).val());
});
console.log("Sum:"+sum);
var average = sum / counter;
document.getElementById("demo").innerHTML = average;
let header=$("tr#tr"); // same as $.find("tr[id='tr2']")
$('#thb').before("<th data-id='headers' id='headerss'>Average</th>");
}
</script>
ive got this result
this is what i want in my result

Kindly update your JavaScript compute function as shown below.
<script>
function compute(){
let header=$("tr#tr"); // same as $.find("tr[id='tr2']")
$('th:last-child').after("<th data-id='headers' id='header'>Average</th>");
let rows1=$(".tr2");
rows1.append("<td data-id='row' ><input type='number' class='averages'/></td>");
$('tr').each(function () {
var sum = 0
var i=0;
$(this).find('.average').each(function () {
var textVal = $(this).val();
console.log(textVal);
if (!isNaN(textVal) && textVal.length !== 0) {
sum += parseFloat(textVal);
}
i++;
});
var avg=sum/i;
$('.averages', this).val(avg);
});
}
</script>

I would do something like this (using react instead of jquery)
const App = () => {
const [ students, setStudents ] = React.useState([{
id: 0,
name: 'Jonh',
notes: [
{ date: '2020-01-02', note: 4 },
{ date: '2020-01-03', note: 12 }
]
}]);
const [ days, setDays ] = React.useState([
'2020-01-02',
'2020-01-03'
])
const [ newStudentName, setNewStudentName ] = React.useState('Name')
const getAverage = notes => {
return notes.reduce((sum, { note }) => sum + parseInt(note), 0)/notes.length;
}
const addStudent = () => {
setStudents([
...students, {
id: +new Date(),
name: newStudentName,
notes: days.map(date => ({ date, note: null }))
}
])
}
const setNote = (studentId, noteDate, newNote) => {
const nextStudents = students.map(student => {
if (student.id === studentId) {
return {
...student,
notes: student.notes.map(({ note, date }) => (
date === noteDate ? { note: newNote, date } : { note, date }
))
}
}
return student;
})
setStudents(nextStudents)
}
return (
<div>
<table>
<tr>
<th>Name</th>
{days.map(day => <th>{day}</th>)}
<th>Average</th>
</tr>
{students.map(({ id: studentId, name, notes })=> (
<tr>
<td>
{name}
</td>
{notes.map(({ date, note }) => <td><input type="number" onChange={({ target: { value }}) => setNote(studentId, date, value)} value={note} /></td>)}
<td>{getAverage(notes)}</td>
</tr>
))}
</table>
<input onChange={({target: { value }}) => setNewStudentName(value)} value={newStudentName} />
<button onClick={() => addStudent()}>Add student</button>
</div>
)
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related

Display data in a table from localStorage without repeating

I am making a shopping list in my web page where I add the items which I store in localStorage.The items are displayed in a table.The problem is that for each new item added it is showing also the data previously stored again.
My html is:
<form class="market">
<label>Nume produs</label>
<input type="text" id="np">
<label>Cantitate</label>
<input type="text" id="cp">
<input type="button" onclick="addItem();" id="adauga" value="Adaugă" />
</form>
<table>
<tbody id="shopping">
<tr>
<th>Nr.</th>
<th>Name</th>
<th>Quantity</th>
</tr>
And this is the function called on every button click
class Produs{
constructor(id, nume, cantitate){
this.id = id;
this.nume = nume;
this.cantitate = cantitate;
}
}
function addItem(){
let nume = document.getElementById("np").value;
let cantitate = document.getElementById("cp").value;
let produse = localStorage.getItem('produse');
if(produse == null){
produse = [];
}
else{
produse = JSON.parse(produse);
}
produse = produse.map((p) => {
return new Produs(p.id, p.nume, p.cantitate);
});
let lastId = localStorage.getItem('lastId');
if(lastId == null)
{
lastId=1;
}
else{
lastId = JSON.parse(lastId);
}
let id = lastId;
produse.push(new Produs(id, nume, cantitate));
localStorage.setItem('produse',JSON.stringify(produse));
localStorage.setItem('lastId',JSON.stringify(lastId+1));
var jsonData = JSON.parse(localStorage.getItem('produse'));
console.log(jsonData);
for(var i=0; i<jsonData.length; i++)
{
document.getElementById("shopping").innerHTML +="<tr><td>"+jsonData[i].id +"</td><td>" + jsonData[i].nume +"</td><td>"+jsonData[i].cantitate+"</td></tr>";
}
}

Why does the method of adding goods work incorrectly?

When the listener "buttAdd.addEventListener" for the add method is triggered: , first this condition works several times(works with the second addition):
if (inputsAdd [0].value ===""||inputsAdd [1].value ===""||inputsAdd [2]
.value === "")
{alert ("fill all fields");}
It works when the fields are not empty, and then the product is added. And if you click on the add button with empty fields, then the product that was added earlier - will be lost. The same story awith the method, delete. Help me please to fix it
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
Product.SORT_ORDER_ASC = 1;
Product.SORT_ORDER_DESC = -1;
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
this.formAdd = document.forms[0];
this.inputsAdd = this.formAdd.elements;
this.buttAdd = this.formAdd.elements[3];
this.formDelete = document.forms[1];
this.nameDelete = this.formDelete.elements[0];
this.buttDelete = this.formDelete.elements[1];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
//method for sorting the product at its price
sortProductsByPrice(sortOrder) {
const sorted = this.products.sort((a, b) => {
return a.price > b.price ? sortOrder : -sortOrder;
});
this.products = sorted;
}
// method to draw the table with product property (
// name, count, price)
show() {
// add new product by click
this.buttAdd.addEventListener('click', (e) => {
e.preventDefault();
if (this.inputsAdd[0].value === "" || this.inputsAdd[1].value === "" || this.inputsAdd[2].value === "") {
alert("fill all fields");
} else {
this.addProduct(new Product(this.inputsAdd[0].value, parseInt(this.inputsAdd[2].value),
parseInt(this.inputsAdd[1].value)));
this.show();
this.inputsAdd[0].value = "";
this.inputsAdd[1].value = "";
this.inputsAdd[2].value = "";
}
}, false);
// delete product by name after click
this.buttDelete.addEventListener('click', (e) => {
e.preventDefault();
if (this.nameDelete.value === "") {
alert("write a name of product what you want to delete");
} else {
this.deleteProductByName(this.nameDelete.value);
this.show();
this.nameDelete.value = "";
}
}, false);
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
const tFoot = table.querySelector('tfoot');
if (tFoot) tFoot.remove();
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr><td colspan="3" id="total-price">Total price:
${this.totalProductsPrice}</td></tr></tfoot>`;
//filter products by price
document.addEventListener("click", (e) => {
let elem = e.target;
if (elem.id === "filter") {
this.sortProductsByPrice(Product.SORT_ORDER_ASC);
this.show();
}
}, false);
console.log(this.products);
}
}
let shop = new Shop();
shop.addProduct(new Product("product", 1, 2000));
shop.addProduct(new Product("product1", 2, 500));
shop.addProduct(new Product("product2", 3, 1000));
shop.show();
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add" type="button">Add</button><!-- *** -->
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>
See, you're defining let shop = new Shop() and then use this variable in your Shop class, like shop.show(). I strongly recommend you to use this keyword instead of scoped variable (valid for all other shop usage entries).
Now, about
works several times
I assume, that when you call the show() method it registers more event listeners some time. I mean, you call show - it creates new event listeners + sometimes calls itself (huh, it is pretty risky). I suggest you to move listeners declaration to the constructor - so they will be instantinated once (but that will require keeping DOM nodes). Also it would be nice to split your show fucntion to several smaller functions and get rid of self function emit (it will reduce complexity).

Why sorting by price not work?

In the sortProductsByPrice (sortOrder) method, sorting does not work when I delete or add new products, sorting works only for products that are in the this.products array by default.
(Products are sorted by clicking <th> Price: </ th>).
It is necessary that sorting can use too after removal / addition of goods.
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
Product.SORT_ORDER_ASC = 1;
Product.SORT_ORDER_DESC = -1;
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
//method for sorting the product at its price
sortProductsByPrice(sortOrder) {
const sorted = this.products.sort((a, b) => {
return a.price > b.price ? sortOrder : -sortOrder;
});
this.products = sorted;
}
// method to draw the table with product property (
// name, count, price)
show() {
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
const formDelete = document.forms[1];
const nameDelete = formDelete.elements[0];
const buttDelete = formDelete.elements[1];
const priceFilter = document.getElementById("filter");
// add new product by click
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
shop.addProduct(new Product(inputsAdd[0].value, parseInt(inputsAdd[2].value),
parseInt(inputsAdd[1].value)));
shop.show();
}, false);
// delete product by name after click
buttDelete.addEventListener('click', (e) => {
e.preventDefault();
shop.deleteProductByName(nameDelete.value);
shop.show();
}, false);
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
const tFoot = table.querySelector('tfoot');
if (tFoot) tFoot.remove();
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr><td colspan="3" id="total-price">Total price:
${shop.totalProductsPrice}</td></tr></tfoot>`;
priceFilter.addEventListener("click", (e) => {
shop.sortProductsByPrice(Product.SORT_ORDER_ASC);
shop.show();
}, false);
}
}
let shop = new Shop();
shop.addProduct(new Product("product", 1, 2000));
shop.addProduct(new Product("product1", 2, 500));
shop.addProduct(new Product("product2", 3, 1000));
shop.show();
console.log(shop.products);
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>
It is necessary that sorting can use too after removal / addition of goods
The sorting is not working after addition/removal because you are calling show() method after adding/removing element, which will redraw the whole HTML, without attaching any events to it, so the originally attached event handlers will be unbound.
You need to attach the event handlers in your show() method to resolve this problem.
And there's no need to return the sorted array in your method, the original this.products will be sorted in place.
So there's no need to declare sorted array, and return it, just write the this.products.sort() code it will sort the array.
sortProductsByPrice(sortOrder) {
this.products.sort((a, b) => {
return a.price > b.price ? sortOrder : -sortOrder;
});
}
Demo:
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
Product.SORT_ORDER_ASC = 1;
Product.SORT_ORDER_DESC = -1;
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
//method for sorting the product at its price
sortProductsByPrice(sortOrder) {
this.products.sort((a, b) => {
return a.price > b.price ? sortOrder : -sortOrder;
});
}
// method to draw the table with product property (
// name, count, price)
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
const tFoot = table.querySelector('tfoot');
if (tFoot) tFoot.remove();
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr><td colspan="3" id="total-price">Total price:
${shop.totalProductsPrice}</td></tr></tfoot>`;
}
}
// add new product by click
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
shop.addProduct(new Product(inputsAdd[0].value, parseInt(inputsAdd[2].value),
parseInt(inputsAdd[1].value)));
shop.show();
}, false);
// delete product by name after click
const formDelete = document.forms[1];
const nameDelete = formDelete.elements[0];
const buttDelete = formDelete.elements[1];
buttDelete.addEventListener('click', (e) => {
e.preventDefault();
shop.deleteProductByName(nameDelete.value);
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product", 1, 2000));
shop.addProduct(new Product("product1", 2, 500));
shop.addProduct(new Product("product2", 3, 1000));
shop.show();
const priceFilter = document.getElementById("filter");
//filter products by price
priceFilter.addEventListener("click", (e) => {
shop.sortProductsByPrice(Product.SORT_ORDER_ASC);
shop.show();
}, false);
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name">Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>

Why does not work method of deleting items by name?

The method of removing products by their name does not work. I'm trying to delete using buttDelete.addEventListener but the deletion does not happen.
The logic of the deleteProductByName method is that when the name of product is received from input nameDelete it is checked the same products in shop.products array, then when the button delete is press (buttDelete), the product is deleted from the array and correspondingly from the table too, if the field is empty, then output alert that you need to fill out the field.
Help please fix that
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
// method to draw the table with product property (
// name, count, price)
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr id="total-price"><td colspan="3">Total price:
${shop.totalProductsPrice}</td></tr></tfoot>`;
}
}
// add new product by click
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
shop.addProduct(new Product(inputsAdd[0].value, parseInt(inputsAdd[2].value),
parseInt(inputsAdd[1].value)));
shop.show();
}, false);
// delete product by name after click
const formDelete = document.forms[1];
const nameDelete = formDelete.elements[0];
const buttDelete = formDelete.elements[1];
buttDelete.addEventListener('click', (e) => {
e.preventDefault();
shop.deleteProductByName(nameDelete.value);
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.show();
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>
Then I would use a console.log() or a debugger on
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
console.log("productName " + productName + "this.products[i].name" + this.products[i].name);
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
to see if you comparing the same names. To make sure your if statement is working as expected.

Checkbox default checked state issue

I am having the following code. There's some issue I'm facing right now with this thing in my project. I want to use the forEach() loop there inside getElements() instead of map() and also I want to simply show it default checked whenever after checking on a checkbox, going next and again returning back there.
Any help with this issue ??
here's the => DEMO
import React, { Component } from 'react';
import { render } from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Checkbox from 'material-ui/Checkbox';
class App extends Component {
itemsPerPage = 4
constructor(props) {
super(props);
var ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.state = {
ids: ids,
idsChecked: ids.map(() => false),
page: 0
}
}
componentDidMount = () => {
}
handlePrevious = () => {
this.setState({ page: this.state.page - 1 });
}
handleNext = () => {
this.setState({ page: this.state.page + 1 });
}
handleCheck = (e) => {
var id = Number(e.currentTarget.id);
var idsChecked = this.state.idsChecked.map((bool, i) => i === id ? !bool : bool);
this.setState({ idsChecked: idsChecked });
}
handleDetails = (e) => {
var id = Number(e.currentTarget.getAttribute("rel"));
console.log("even or odd is clicked! (button #id: " + id + ")");
}
getElements = () => {
var first = this.state.page * this.itemsPerPage;
var trs = this.state.ids.slice(first, first + this.itemsPerPage).map((element, i) => {
let details = <button rel={first + i} onClick={this.handleDetails}> {element % 2 ? "odd" : "even"} </button>;
return (
<tr key={element}>
<td><Checkbox
checked={this.state.idsChecked[first + i]}
id={first + i}
onCheck={this.handleCheck}
/></td>
<td>{element}</td>
<td>{details}</td>
</tr>
);
});
return trs;
}
render() {
var hasPrevious = this.state.page > 0;
var hasNext = this.state.page < Math.floor((this.state.ids.length - 1) / this.itemsPerPage);
var tdStyle = {width: "80px"}
return (
<div>
<div>
<table>
<tbody>
<tr>
<td style={tdStyle}>{hasPrevious && <button onClick={this.handlePrevious} hidden={this.state.hasPrevious}> Previous </button>}</td>
<td style={tdStyle}>{hasNext && <button onClick={this.handleNext} hidden={this.state.isNext}> Next </button>}</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
{this.getElements()}
</tbody>
</table>
</div>
</div>
);
}
}
render(<MuiThemeProvider><App /></MuiThemeProvider>, document.getElementById('root'));
To replace, map with forEach, push the checkbox elements onto an array, and return that array from your getElements().
Use the defaultChecked props of the <Checkbox> component to set the default value to true.
Full code:
getElements = () => {
var first = this.state.page * this.itemsPerPage;
let checkboxArray = []; // array for storing the elements
this.state.ids.slice(first, first + this.itemsPerPage).forEach((element, i) => {
let details = <button rel={first + i} onClick={this.handleDetails}> {element % 2 ? "odd" : "even"} </button>;
checkboxArray.push(
<tr key={element}>
<td><Checkbox
checked={this.state.idsChecked[first + i]}
id={first + i}
defaultChecked={true/*use the defaultChecked prop*/}
onCheck={this.handleCheck}
/></td>
<td>{element}</td>
<td>{details}</td>
</tr>
);
});
return checkboxArray; // return the array
}
render() {
var hasPrevious = this.state.page > 0;
var hasNext = this.state.page < Math.floor((this.state.ids.length - 1) / this.itemsPerPage);
var tdStyle = {width: "80px"}
return (
<div>
<div>
<table>
<tbody>
<tr>
<td style={tdStyle}>{hasPrevious && <button onClick={this.handlePrevious} hidden={this.state.hasPrevious}> Previous </button>}</td>
<td style={tdStyle}>{hasNext && <button onClick={this.handleNext} hidden={this.state.isNext}> Next </button>}</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
{this.getElements()}
</tbody>
</table>
</div>
</div>
);
}
}

Categories