How to change the value of the currently selected item in the list box?

会有一股神秘感。 提交于 2019-12-13 00:40:43

问题


I know one can get the value of the currently selected item like this:

var myListBoxItemText = $('#myListBox').val().toString();

But how do you change this value in the list box to something else?


回答1:


Seeing your update in the comments, here's an updated answer. Just use the :selected selector to filter the options inside of your select element to get the selected option.

To change a select element's selected option's value property:

 $('#myListBox option:selected').val('new value');

To change its display text:

 $('#myListBox option:selected').text('new text');

JSFiddle




回答2:


$("#myListBox").val("This is the new value");

Although, by 'listbox', I assume you mean a select element. In which case you'll have to add the property selected to one of the child option elements.




回答3:


$('#myListBox').val(your_val);

Here your_val denotes the value attribute of <option>

Or you can also use

$('#myListBox')[0].selectedIndex = 1;

or

  $('#myListBox').prop('selectedIndex', 1);

DEMO

DEMO 2



来源:https://stackoverflow.com/questions/10939731/how-to-change-the-value-of-the-currently-selected-item-in-the-list-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!