skip to Main Content

radio box input doesn’t store the value instead shows "on" in the database
here is my code.

            <label for="gender">Female</label>
            <input type="radio" name="gender">
            <label for="gender">Male</label>
            <input type="radio" name="gender">
            <label for="gender">Transgender</label>
            <input type="radio" name="gender">
            <span class="formerror"></span>

this is my schema

gender: {
        type: String,
        required: true
      }

this is the data in the database stored

{
  name: 'Ethan Hunt',
  age: 60,
  gender: 'on',
  blood_group: 'B+',
  date: 2023-07-05T00:00:00.000Z,
  phone_number: '7074788341',
  medical_history: 'cataract',
  password: '1234',
  _id: new ObjectId("64a1bced4796f50508c67030"),
  __v: 0
}

i was expecting the gender value to show up as "male" "female" or "transgender".

i also tried adding

gender: {
        type: String,
        enum: ["female", "male", "transgender"],
        required: true
      },

but it generates an error
"Detail validation failed: gender: on is not a valid enum value for path gender.
at ValidationError"

2

Answers


  1. give your html element a "value" attribute and set it’s value to the gender value it denotes.

    also read: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
    for more insight on accessing the value via javaScript

    Login or Signup to reply.
  2. You need to give each option/radio button a value. And now you can ask for the value on the name (gender). The e.target in the submit event callback is the form element.

    The for attribute on <label> only work for IDs. Skip the IDs and have the input as a child to label will work fine.

    document.forms.form01.addEventListener('submit', e => {
      e.preventDefault();
      console.log(e.target.gender.value);
    });
    <form name="form01">
      <label>Female <input type="radio" name="gender" value="female" required></label>
      <label>Male <input type="radio" name="gender" value="male"></label>
      <label>Transgender <input type="radio" name="gender" value="transgender"></label>
      <button type="submit">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search