Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to read checkbox data in NodeJS

I have a form on my webpage and its being submitted to a NodeJS backend. I'm having trouble with the checkboxes. When the are submitted to server, and I read them via req.body.foods, I get something like ['on', 'on', 'on'].

But I want to get the actual values, that is, something like ['dairy', 'fish'] etc.

How can I do that?

<div class="col-sm-6">
    <div class="checkbox">
        <label><input name="food" type="checkbox" value="dairy">Dairy</label>
    </div>
    <div class="checkbox">
        <label><input name="food" type="checkbox" value="meat">Meat</label>
    </div>
    <div class="checkbox">
        <label><input name="food" type="checkbox" value="fish">Fish</label>
    </div>
</div>
like image 719
CodyBugstein Avatar asked Oct 31 '22 08:10

CodyBugstein


1 Answers

You can do the following in the node.js file:

console.log(req.body.food); //This will print the array of values.

If you have only one checkbox selected in the page, (eg: Dairy) it will print "dairy". If more than one checkbox, then you get "{ 'dairy', 'meat' }" in the output. Make sure the checkboxes are within the form.

Another method:

Include a hidden input element in your form:

<input name="SelectedValues" type="hidden" value="">

Also include a call to a javascript file in the onchange event of every checkbox, or in the onclick event of the submit button in the form.

onclick='buildlist("YourCheckBoxName","SelectedValues");'

Use a javascript function to loop through your checkbox and build a comma separated list of selected values:

function buildlist(listName,labelName){
  var controls = document.getElementsByName(listName);
  var label = document.getElementsByName(labelName);
  label.value = '';
  for(var i=0;i<controls.length;i++){
     label.value += controls[i].value.toString()+',';
  }
}

Now inside the node.js file, use the following code to access the list of values:

req.body.SelectedValues
like image 142
Abhijith C R Avatar answered Nov 09 '22 16:11

Abhijith C R