简体   繁体   English

在Javascript / Node.js中获取选定的选项

[英]Getting the selected option in Javascript/Node.js

Self teaching Node.js and Javascript stuff. 自学Node.js和Javascript内容。 I have in the form in my HTML and select, drop down menu option. 我在HTML中的表单中选择了下拉菜单选项。 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. 我有req.body在文本框中获取输入的值,但它告诉我selectedIndex不是问题。 So then I tried: 因此,我尝试了:

var e = req.body.boolean_choice

to see what that gave and it just gave undefined . 看看给出了什么,给出了undefined

Is there a way to do this? 有没有办法做到这一点?

Here is the HTML: 这是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. 表单提交将仅通过选择的value属性。 Also use debugger in IDE that you use, to explore req.body , instead of trying to guess what's there. 还可以在您使用的IDE中使用调试器来浏览req.body ,而不是尝试猜测其中的内容。

Happy to help. 乐意效劳。

First of all get the Selected option DOM element 首先获取Selected选项的DOM元素

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

ibn your case it will be req.body.querySelector('#choice option:selected'); 如果您的情况是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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