Tuesday, 15 July 2014

html - Proper way to read checkbox data in NodeJS -


I have a form on my webpage and it is being submitted in the nodes backend. '

There is a problem with the check box when the server is submitted, and I have read them through req.body.foods , give me the code [ Something like 'on', 'on', 'on'] is anything like.

But I want to get real values ​​such as ['dairy', 'fish'] etc.

How can I do that?

  & lt; Div class = "col-sm-6" & gt; & Lt; Div class = "checkbox" & gt; & Lt; Label & gt; & Lt; Input name = "food" type = "checkbox" value = "dairy" & gt; Dairy & lt; / Label & gt; & Lt; / Div & gt; & Lt; Div class = "checkbox" & gt; & Lt; Label & gt; & Lt; Input name = "food" type = "checkbox" value = "meat" & gt; Meat & lt; / Labels & gt; & Lt; / Div & gt; & Lt; Div class = "checkbox" & gt; & Lt; Label & gt; & Lt; Input name = "food" type = "checkbox" value = "fish" & gt; Fish & lt; / Labels & gt; & Lt; / Div & gt; & Lt; / Div & gt;  

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 (like: dairy), it will print "dairy". If more than one checkbox, you get "{Derry," 'meat'} "in the output.

Another method:

Include hidden input elements in your form:

  & lt; Input name = "selected value" type = "hidden" value = "" & gt;  

Include this in the on-event event of each checkbox or in the Javascript file in the call, or on the on click event of the submit button in the form.

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

Use the JavaScript function to loop through your checkbox and create a comma separated list of selected values:

  function buildlist (list name, label name) {Var Control = Document.getElementsByName (listName); Var label = document. GetElementsByName (labelName); Label.value = ''; (Level i = 0; i & lt; controls.length; i ++) for (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 ​​ 

No comments:

Post a Comment