简体   繁体   中英

Getting the selected option in Javascript/Node.js

Self teaching Node.js and Javascript stuff. I have in the form in my HTML and select, drop down menu option. How do I get the index of the selected value?

So far im trying this:

var e = req.body.boolean_choice;
boolChoice = e.selectedIndex;

I have the req.body working for getting the inputted values in a text box, but it tells me selectedIndex is not a thing. So then I tried:

var e = req.body.boolean_choice

to see what that gave and it just gave undefined .

Is there a way to do this?

Here is the HTML:

<form action="http://localhost:3000" method="POST">
Form:<br>
<br>
<br>
Text Box 1: <input type="text" name="tb1"  size="35" placeholder="&quot;@10SadioMane&quot; OR &quot;#Mane&quot;">
<br>
<br>
<select id="choice" name="choice">
  <option value="OR">OR</option>
  <option value="AND">AND</option>
</select>
<br>
<br>
<input type="submit" value="Submit">

Form submitting will pass only value property of selection. Also use debugger in IDE that you use, to explore req.body , instead of trying to guess what's there.

Happy to help.

First of all get the Selected option DOM element

var el = document.querySelector('#choice option:selected');

ibn your case it will be req.body.querySelector('#choice option:selected');

Now logic is to iterate to the previous siblings in the chain till you reach to the top.

var index = 0; 
while( el.previousSibling ! == null){
el = el.previousSibling;
index +=1;
}
console.log(index);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM