Search code examples
htmlmysqlnode.jsexpresshandlebars.js

How to insert into SQL a checkbox in a form with Handlebars?


I have a form that edits a product: edit_product

And when it's edited, it uploads it by updating this SQL table (called product).

enter image description here

The problem becomes when I want to post the checkbox. In the form, all is submited correctly, except the checkbox, that always gets the value of 0.

Here's a screenshot of a console.log, the checkbox is is_available value and it's a Boolean.

enter image description here

In the form, the checkbox is:

<div class="form-group">
<input type="checkbox" name="is_available" {{#if product.is_available}}checked{{/if}}>
</div>

And the function that receives the form by POST method:

router.post('/edit/:id', isLoggedIn, async(req,res) => {
    const { id } = req.params;
    const { title, url, image_path, description, price, coupon, discount, is_available } = req.body;
    const newProduct = {
        title,
        url, 
        image_path,
        description,
        price,
        coupon,
        discount,
        is_available
    };
    await pool.query('UPDATE product SET ? WHERE id = ?', [newProduct, id]);
    req.flash('success', 'Product modified successfully');
    res.redirect('/products/');
});

I want to know why the checkbox value isn't UPDATING in the DATABASE when checkbox is on/off.


Solution

  • the checkbox does not have a value attribute, which will send the value 'on' if it was checked. if the checkbox is not checked, it will not send the value at all in the post request.

    what you can do is change the function that receives the request and change the value of is_available to either zero or one depending if it was sent in the POST request.