jquery 将选项值设置为选定[重复]

f4t66c6m  于 2024-01-07  发布在  jQuery
关注(0)|答案(3)|浏览(214)

此问题在此处已有答案

Change the selected value of a drop-down list with jQuery(19个回答)
上个月关门了。
我想加载一个选择框中的用户的选定值将自动出现。
我正在从服务器接收一个包含用户信息的JSON数据。数据示例为:{"color":"red"}
在我的HTML代码中,我有这样的选择选项:

  1. <select id="input_user" class="selectinput" disabled="true">
  2. <option value="n/a"> n/a </option>
  3. <option value="red"> red </option>
  4. <option value="green"> green </option>
  5. <option value="yellow"> yellow </option>
  6. <option value="blue"> blue </option>
  7. <option value="white"> white </option>
  8. </select> //this will only show "n/a" as default

字符串
我试着用这段代码把红色的值设为默认值,但是没有用。

  1. var user_color= data[2].color; // this was from the json data
  2. document.getElementById('input_user').selectedIndex = user_color;


有什么需要帮忙的吗?

yrefmtwq

yrefmtwq1#

因为你已经用jQuery标记了这个问题,你可以直接在select上设置val()

  1. var user_color = 'red'; //data[2].color;
  2. $('#input_user').val(user_color);

个字符

0dxa2lsx

0dxa2lsx2#

经过大量的研究,我终于回去看了jQuery文档,它给了我正确的答案:
1 /删除已经具有“selected”属性的标签的所有属性

  1. function remove_selected(){
  2. $("select option").removeAttr('selected');
  3. }

字符串
2 /我使用jQuery的prop()函数将'selected'属性分配给所需的标记

  1. // USE THE FUNCTION TO REMOVE ALL ATTRIBUTES ALREADY SELECTED
  2. remove_selected();
  3. // Set the tag <option> attribute to 'selected'
  4. $('select option[value="ThatYouWant"]').prop({defaultSelected: true});


在HTML中,这给出:

  1. <select>
  2. <option value="something">Something</option>
  3. <option value="ThatYouWant" selected>That you want</option>
  4. <option value="OtherValue">Other value</option>
  5. </select>


它是干净的,没有灰尘,感谢您的反馈和更正,批准如果你发现这个解决方案正确。真诚的,拉夫。
来源:https://api.jquery.com/prop/

展开查看全部
qyyhg6bp

qyyhg6bp3#

更简单的方法如下:

  1. $("#input_user").val("red").trigger("change");

字符串
只需要在val()中传递你想作为选择值的值。

相关问题