How to Get Values of Checkbox in Node Js Using Ejs

How to get value of checkbox plus another value together from ejs with express

Got the answer : Pass the additional attribute as hidden property.

Retrieving value from input in EJS with NodeJS

  1. That is the default behaviour of the checkbox, it only gets
    passed as data if its checked, if it doesn't get passed, we can
    assume it wasn't checked

    • However if you still want the checkbox in data even if it was not checked, one hack would be

      • Create a hidden element with same name as your checkbox & set value as 'off'
      • Before submit, if the checkbox is checked, disable the hidden input element
      • this will give your checkbox value 'on' when checked & 'off' when its not
  2. As mentioned above, it will only added to formdata if its
    checked, when its not checked, the element is not added to formdata
    at all, so you will get undefined if its not checked

  3. Again this is default behaviour of input types, the reason it
    does not do same for checkbox is because, maybe you are only
    selecting 1 checkbox with same name before submit, if you do select
    multiple checkbox with same name in checkboxes, you'll get same
    result for checkboxes too, but due to the reason mentioned in first
    answer, it only get's us the element selected which is 1 in your
    case

How to present checkbox values in HTML (using ejs) after extracting data from mongo for User to Edit?

The input type checkbox takes the attribute checked as true, even if you don't assign any value to it.

So, you may need to do something like

<input id="opt1" type="checkbox" name="check1" <%= question.options.option1.check ? "checked" : "" %> />

Let me know if that worked for you. If the conditional couldn't be evaluated inside the <%= %> ejs tag, you may need to evaluate the conditional and storing in another variable before displaying it:

<% let checked = question.options.option1.check ? "checked" : "" %>
<input id="opt1" type="checkbox" name="check1" <%= checked %> />

How do I handle an array of checkboxes in ejs

You could set the initial values on the input element itself.

For this example, I'll assume you have a value coming in to indicate whether an announcement is "enabled" or not:

<td>
<input type="checkbox" id="enabled<%= i %>" name="enabled[<%= i %>]" <%= announcement.enabled ? "checked" : null %> >
</td>

That's a little terse - here's an alternative example that does the same thing:

<td>
<input type="checkbox" id="enabled<%= i %>" name="enabled[<%= i %>]" <% if (announcement.enabled) { %> "checked" <% } %> >
</td>


Related Topics



Leave a reply



Submit