mercredi 21 novembre 2018

Save checked Chechbox into sqlite database with javascript

I have a form in my ejs with several checkboxes. In the application the user should be able to choose his interests by checking the checkboxes and this should be saved into a sqlite Database table. I'm building the table via bootstrap:

db.exec('CREATE TABLE interests(interest text)');

(not sure which type to choose, so I set it to "text", but this is probably wrong?). My Form looks like this

<form name="first_steps" action="first_steps" method="post">
  <ul>
    <li>
        <input type="checkbox" name="interesse" value="theater" id="check1">Theater</label>
    </li>
    <li>
        <input type="checkbox" name="interesse" value="musik" id="check2">Musik</label>
    </li>
    <li>
        <input type="checkbox" name="interesse" value="party" id="check3">Party</label>
    </li>
    <li>
        <input type="checkbox" name="interesse" value="sport" id="check4">Sport</label>
    </li>
</ul>
<input type="submit" value="submit">

I found this Article Save result checkboxes checked in form into sqlite database with javascript and tried to convert this into my server.js

(Something like this

app.post('/first_steps', function(req, res) {
var elementen = document.getElementsByName ("interesse");
var tmpChoise;
for (var r= 0; r < elementen.length; r++) {
    if (elementen[r].checked) {
    tmpChoise = elementen[r].value;
    alert(tmpChoise);
    db.run(`INSERT INTO interessen(interesse) VALUES (?)`, [interesse], function(err) {
            return res.redirect('/profil');
        });
  }
 } 
});

but this doesn't work. It says "ReferenceError: document is not defined").

Can someone tell me how the right code would look like? I'm a bloody beginner and couldn't really figure anything out.

(Javascript, express, sqlite3, node.js)




Aucun commentaire:

Enregistrer un commentaire