0

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.

enter image description here

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

8 Comments

thanks, now why am I not seeing the one that says selected, selected. The first option is the one displayed
Not sure I understand the question. In my example the selected option is "B", and the value there is 2.
I have added a screenshot with the issue. Selected in DOM is 1 but in UI is 0 @Dekel
The selected attribute will not change when changing the selected option on a select element (this is one of the reasons to work with val()).
val() is still returning a wrong value (0) and what I see in the UI differs of what I see in the DOM. I want to have 1 selected by default, this is OK in DOM but in UI is different. Take a look at the code I've updated
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.