Setting the text of an <option> element using jQuery

邮差的信 提交于 2020-05-11 04:15:20

问题


Using jQuery what is the best way of editing option text for a given select value.

I know the value of the option I want to edit. I thought it would be something like...

$('#select').val().$('option').html('New Text');

But I am clearly missing something.


回答1:


$('#select option[value="someValue"]').text("newText")

could use .html instead of .text, if adding html content.




回答2:


Something like this?

$('#select').children('option').text('New Text');

Have a look at Selectors for more information on selecting the correct item. You could do something like

$('#select').children('option:first').text('New Text');

Or you can use

$('#select').children('option[value="thevalue"]').text('New Text');

If you know the value.




回答3:


You're probably looking for the :selected selector and the text() method:

$("#select option:selected").text("New Text");



回答4:


This one help you to get the options value,

$('#select_id').children('option[value="thevalue"]').text('New Text');

And you can set default selected value by using prop() function. Take an example here.



来源:https://stackoverflow.com/questions/5380704/setting-the-text-of-an-option-element-using-jquery

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