问题描述:

In a django form, I have set the default option for a select. It is not showing those changes in UI, but after inspecting I'm seeing that the DOM is actually being changed. When I check in the console for the HTML, I can see that the selected option is set to 1, but when I ask jquery for the selected option it gives me another.

$("select[name=spread_format] option")

[<option value=​"0">​in.​</option>​, <option value=​"1" selected=​"selected">​ft.​</option>​]

$("select[name=spread_format] option:selected")

[<option value=​"0">​in.​</option>​]

$("select[name=spread_format]").val()

"0"

What I want to accomplish is to show 1 as default. This select is being rendered in a bootstrap modal.

Strange to notice that the selected option in UI is '0', not '1' as indicated my DOM.

网友答案:

In order to get the value of the selected option you should use val(), and not searching for the <option> element.

$('#btn1').click(function() {
  console.log($('#s1').val());  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
  <option value="1">A</option>
  <option value="2" selected="selected">B</option>
  <option value="3">C</option>
</select>
<br />
<button id="btn1">click</button>
相关阅读:
Top