简体   繁体   中英

Option selected != .val from jquery

I am wondering how this is possible, am I missing something? I have a select element and the option selected by default is the empty one on top, see screen shot below.

在此处输入图片说明

but when I inspect that element to see what's the selected option it displayed 13 as the value.

在此处输入图片说明

For a little background on the the problem and what I am doing; on the first page I am selecting a value bases on drop down containing the groups shown in the image. I then navigate to a different page and pass in the selected value as a parameter value in the url. The next page has a page load that set up the page and on the pre-render event I set that select control's value to "" as oppose to the values passed in the url's parameter. So I was expecting the select element to be the top one, and checking the dom it is true. But when using jquery it returns me the value I passed from the previous page. I thought that it was a jquery issue so I used raw java script and it returns me the selected value from the previous page ( see screen shot below).

在此处输入图片说明

Another thing I tried was in my code, drpCtrl.SelectedValue = valStr , where I set the valStr to "" when OnPreRenderComplete is fired, I set it to a hard coded value and that forced the drop down to select the right one as expected, the the previous one passed from the previous page.

This lead me to thinking that there must be a document.ready somewhere setting the value when it is "" . So I started looking and as as of now have not found anything. But then I keep thinking, how can this be? I know the selected value can be changed without changing which option has the selected attribute. That is why $(...).val() , and $(... option:selected).val() can return different values. And my experience has always been that $(... option:selected).val() returns the option with selected attribute.

Does anyone know what is happening here? Is it setting the value to "" ?

:selected will get the element which has the selected prop set to true, [selected] will get the element which has the selected attribute .

 $(function() { $('select').val('12'); console.log($('option:selected').val()); console.log($('option[selected]').val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option selected/> <option value="12">12</option> </select> 

jQuery .val()函数对选择列表进行操作,而不对option元素进行操作,因此,如果您使用以下代码,则代码应该可以工作:

$("#ct100_ct100_contentBody_LendingGroup").val()

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