简体   繁体   English

在选择框中查找选择的值

[英]Finding selected value in a select box

I'm making a quiz application involving a select box. 我正在做一个涉及选择框的测验应用程序。 The user selects an option and when they press a button, it should check if the selected option is the correct answer by checking an array of values. 用户选择一个选项,然后在按下按钮时,应通过检查值数组来检查所选选项是否为正确答案。 I can't figure out how to get the selected value from the select box. 我不知道如何从选择框中获取选定的值。 I've tried to find information about this, but I only want to use JS, no JQuery. 我试图找到有关此的信息,但我只想使用JS,没有JQuery。 I tried using: 我尝试使用:

var item = document.getElementById("selections");
var selection = item.options[item.selectedIndex].value;

but I get a Type Error , saying that item.selectedIndex isn't defined. 但是我收到Type Error ,说item.selectedIndex I'm confused because from what I found, selectedIndex is a default property of select tags? 我很困惑,因为从我发现的结果来看, selectedIndex是选择标签的默认属性? I've only worked with radio buttons before, using a for loop and checking every option to see which was checked, but I can't use that here. 我以前只使用单选按钮,使用for循环并检查每个选项以查看已检查的选项,但是我不能在这里使用它。 I don't know if it matters, but I'm doing this without a form tag, just linking a js function to an event listener on a button. 我不知道这是否重要,但是我是在没有表单标签的情况下执行此操作的,只是将js函数链接到按钮上的事件侦听器。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

Edit: Here is a fiddle of my code as per request: https://jsfiddle.net/jmf68ycu/ 编辑:这是根据请求我的代码的小提琴: https : //jsfiddle.net/jmf68ycu/

The part where the problem lies is in the submit() function in the first line. 问题所在所在的是第一行中的submit()函数。

Update: I found something online about the problem having to do with JS trying to call the element before the element is loaded, so I put the variables inside the function, which is only called when the button is pressed. 更新:我在网上发现了一些与JS有关的问题,该问题与JS试图在加载元素之前调用该元素有关,因此我将变量放入函数中,该函数仅在按下按钮时才调用。 The problem still persists (same error). 问题仍然存在(相同的错误)。

You use like this 你这样使用

var item = document.getElementById("selections").value;

you select value store item variable 您选择值存储项目变量

this code use full for you. 此代码为您充分使用。 :) :)

You have a syntax error somewhere. 您在某处存在语法错误。 your code looks right. 您的代码看起来正确。 you probably aren't getting the right id. 您可能没有获得正确的ID。 your first line probably doesn't return the right select. 您的第一行可能不会返回正确的选择。

 var e = document.getElementById("bla"); var str = e.options[e.selectedIndex].value; alert(str); 
 <select id="bla"> <option value="val1">test1</option> <option value="val2" selected="selected">test2</option> <option value="val3">test3</option> </select> 

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

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