简体   繁体   English

jQuery`.val`报告选择值,未选择任何选项

[英]jQuery `.val` reporting a value for a select, with no option selected

I have a select that looks like this: 我有一个看起来像这样的选择:

<select id   = "baz"
        name = "Baz"
        size = 1>
  <option value="A1"> foo</option>
  <option value="A2"> bar</option>
  ...etc
  <option value="A99"> bat</option>
</select>

I've pulled this code from Firebug (and edited it), as the options themselves are read from the server by a CGI #include . 我已经从Firebug中提取了此代码(并对其进行了编辑),因为选项本身是由CGI #include从服务器读取的。

The value of the select is eventually read by JavaScript as follows: select的值最终由JavaScript读取,如下所示:

var $input_baz = $("#baz");
...
var baz_pl = $input_baz.val();

Problem: the select is in a hidden div, and no selections have been made, but baz_pl contains the value A1 . 问题:选择位于隐藏的div中,尚未进行选择,但是baz_pl包含值A1 Why is .val() returning the first entry when nothing has been selected, and is there a simple fix for this? 为什么在未选择任何内容的情况下.val()返回第一个条目,并且对此有简单的解决方法吗? The select appears in a popup, and I can add code to detect if the popup 'Ok' button has been clicked, but I'd rather do it properly if possible. 该选择出现在弹出窗口中,我可以添加代码以检测是否单击了弹出的“确定”按钮,但我希​​望在可能的情况下正确进行操作。

The first option is always selected by default. 默认情况下,始终选择第一个选项。 You could add a dummy entry as first one, with a value that does not occur otherwise in the list. 您可以添加一个虚拟条目作为第一个条目,其值在列表中否则不会出现。

For example: 例如:

<option value="-1">-- Please select --</option>

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

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