Option value is not able to select using jquery.

20 浏览
0 Comments

Option value is not able to select using jquery.

我有一个可搜索的下拉菜单,我想使用以下查询来选择传递的选项值:

$(#id).val('optiontext').attr('selected',true)

但每次它都会在下拉菜单的搜索文本框中键入,而我需要选择该选项值。

0
0 Comments

除了ID选择器中缺少引号之外,您还需要按文本选择选项:

$("#id option").filter(function() {
  return this.text == 'optiontext'; 
}).attr('selected', true);​

this.text我以前没有听说过这个属性

我正在做同样的事情,但是没有选择

:您可以共享带有相关代码的fiddle吗??

问题的原因是使用jQuery时无法选择选项值。解决方法是使用过滤器函数和.attr()方法来选择选项,并将其设置为选中状态。此外,还需要确保ID选择器中的引号正确使用。以下是解决问题的代码示例:

$("#id option").filter(function() {
  return this.text == 'optiontext'; 
}).attr('selected', true);

请注意,此解决方法仅在使用正确的选择器和属性时有效。如果问题仍然存在,请确保您的代码没有其他错误,并提供相关代码的fiddle以更好地理解问题所在。

0