How to get html select's selected option value with Express.js?

Viewed 768

I'm using a html dropdown in my project. How do I get the select value in the Express server?

<div class="mb-3">
  <label for="kk" class="form-label">Designation</label>
  <select class="form-select" name="picker" aria-label="Default select example" id="kk">
    <option selected>Select</option>
    <option value="1">Proffesor</option>
    <option value="2">Associate Proffessor</option>
    <option value="3">Lab Assistant</option>
  </select>
</div>

In my post request handling method I have used this code to get the value:

const f = req.body.picker;

What this gives me is the index of the selected values in the dropdown like 0,1,2 etc instead of actual values like professor, associate professor,lab assistant.

1 Answers

You actually get what is in value attribute of the selected option when you send your request. For the data you want, you can do it this way:

<div class="mb-3">
  <label for="kk" class="form-label">Designation</label>
  <select class="form-select" name="picker" aria-label="Default select example" id="kk">
    <option value="" selected>Select</option>
    <option value="Proffesor">Proffesor</option>
    <option value="Associate Proffessor">Associate Proffessor</option>
    <option value="Lab Assistan">Lab Assistant</option>
  </select>
</div>

And that is what you will get :

const f = req.body.picker; // -> "" or "Proffesor" or "Associate Proffessor" or "Lab Assistan"
Related