How do I iterate through the checked checkboxes, without hard coding and checking each box one at a time. Kinda like this link, but with Node.js and not JavaScript Iterate all checkbox in JavaScript:
So I'm attempting to display the contents of my database (using MySQL), but I don't want to hard code 'req.body.checkboxName' for every checkbox in case a new column is added onto a table (the checkboxes are each of the columns in a given table). So I need to find a way that will iterate through every checkbox in the webpage and see if it is checked. If it is then we'll add them together in a string and query for those columns. My code below is for the Node.js POST method (after hitting submit once the checkboxes are checked) and the other is my Pug/Jade code (the JavaScript Templating Engine that I use, sorry it isn't plain html).
In case you're confused how the Pug/Jade file runs initially, another GET method renders that Pug/Jade file with the column names; that GET method is basically the POST method below up until the '//Need help' line
Node.js
app.post('/GetTables', function(req, res){
var columnsRequest = 'DESCRIBE ' + tableName;
var columnsList = [];
connection.query(columnsRequest, function(err, results, fields) {
if(err){
throw err;
}
for (var index in results) {
console.log(results[index].Field);
columnsList.push(results[index].Field);
}
});
//Need help, the next 5 or so lines are non-working ~psuedocode
var checkedList = '';
req.body.CHECKBOXES.each(function(index, element){
if(CHECKBOX.ischecked(){
checkedList += CHECKBOX.name() + ', '
}
});
var mysqlRequest = 'SELECT ' + checkedList + ' FROM ' + tableName;
connection.query(mysqlRequest, function(err, results, fields) {
if(err){
throw err;
}
res.render('webPage', {'columnstodisplay': results});
});
});
Pug/Jade
form(method = 'POST', action = '/GetTables', id = 'tableform')
fieldset
each item in columns
//this loop sets up the checkboxes for each of the columns
p
input(type="checkbox", name=item, value=item)
span #{item}
br
input(type ='submit', value ='Submit')
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire