0

Fisrt of all, the value of select is null(no option is selected) and there already exist some options. However, it changes to the value of first option after adding a new option into select through jquery and vue respectively, why? (we tested this case on chrome)

1.

<select>
    <option val="a">a</option>
    <option val="b">b</option>
<select>

at this time:

$("select").val() == null
  1. add an option into select with jquery$("select").append("<option value='hi'>hi</option>")

at this time:

$("select").val() == "a"
Leo
  • 13,428
  • 5
  • 43
  • 61
张庚昕
  • 31
  • 4

1 Answers1

0

By default, HTML prefers to have an option selected. It is likely that you manually set the selectedIndex to -1 for your select which is overridden after appending an element to the select. You have one of two options:

  1. Detect your current selectedIndex and restore it after appending. Something along to lines of var originalSelectedIndex = $("select").prop("selectedIndex"); $("select").append("<option value='...'>...</option>"); $("select").prop("selectedIndex", originalSelectedIndex);.
  2. Create an initial element with an empty label such as <option label=" "></option> which would in essence submit an empty value to your server upon submit.
Ryan Tse
  • 1,559
  • 11
  • 15
  • Appending an option *does not* affect the current selection. It is purely because there was no default option: https://jsfiddle.net/TrueBlueAussie/5dr90fm7/ – iCollect.it Ltd Dec 09 '16 at 12:11
  • The point is that the original post specifically was setting the `selectedIndex` to `-1`, hence by appending an option caused the ` – Ryan Tse Dec 09 '16 at 14:10
  • Who's original post? Not the OP here (they only have one question and no history of selectedIndex = -1 anyway). It would be `null` by default and any nomatch value will select the first entry (if a default one is not present). Also a label is not required as you state in the second part. – iCollect.it Ltd Dec 09 '16 at 14:34
  • The OP's code with the two options listed would not return `null` by default. Since the value being returned initially is `null`, the only way that would have occurred is if the OP specifically set `selectedIndex` to `-1`. Hence by appending an option *it does* affect the current selection. – Ryan Tse Dec 09 '16 at 16:14
  • I have kindly forked your (Gone Coding) version of the code to demonstrate: https://jsfiddle.net/qhbcqhaf/ – Ryan Tse Dec 09 '16 at 16:22