简体   繁体   中英

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 .

The value of the select is eventually read by JavaScript as follows:

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 . Why is .val() returning the first entry when nothing has been selected, and is there a simple fix for this? 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>

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