Ansul
Ansul

Reputation: 420

Get the checkbox value in node.js

I want to access the checkbox value form request.body in node.js. I tried logging it but the console says 'undefined.'

HTML

 <label>
       <input name='sell' type='checkbox' value='false' />I want to sell this photo.
 </label>

Node.js

   const { title, description, category, sell } = req.body;
   console.log(req.body);
   console.log(sell);

The other data from the request body is being logged out but the checkbox (sell) is undefined. I cannot figure out what is wrong..

Upvotes: 0

Views: 967

Answers (1)

Quentin
Quentin

Reputation: 943562

Only successful controls will be submitted to the server.

A checkbox is only successful if:

  • It has a name
  • It is checked

We can see your checkbox has a name, so, since the rest of your data isn't coming through, the problem is that it isn't checked.

Given that you have given it a value of false I'd suspect you might be using client side JS to toggle it's value between true and false. If so, don't do that.

Determine if it is checked or not based on its presence. Force it to a boolean state on the server if you need an explicit boolean.

const booleanSell = !!sell;
console.log(booleanSell).

Upvotes: 1

Related Questions