简体   繁体   English

如何使用jQuery或JavaScript更改选定的值

[英]how to change the selected value using jquery or javascript

I have a that I want to change the selected one late using a function which is trig onClick later in the app. 我有一个我想使用稍后在应用程序中触发onClick的功能来更改选定的一个。

<select id="myselect">
<option value=aa>aa</option>
<option value=bb>bb</option>
<option value=cc>cc</option>
</select>

then by click on a button a function will run and send a query to mysql using php. 然后通过单击一个按钮,函数将运行并使用php将查询发送到mysql。 Let say that php responds me back "bb" then how can I change this select to be selected on bb?? 假设php回复我“ bb”,然后我如何更改此选择以选择bb?

document.getElementById('myselect').value="bb"; 

does not work. 不起作用。

Add an identifier to your select element such as an ID, then you can just set the value with .val() . 向您的选择元素添加一个标识符(例如ID),然后可以使用.val()设置值。

<select id="mySelect">
    <option value="aa">aa</option>
    <option value="bb">bb</option>
    <option value="cc">cc</option>
</select>

In jQuery once you receive your AJAX response, set the value 收到AJAX响应后,在jQuery中设置值

$('#mySelect').val(phpResponseValue);

Where phpResponseValue is the value returned from the AJAX response such as aa . 其中phpResponseValue是从AJAX响应返回的值,例如aa

HTML: HTML:

<select id="mySelect">
<option value=aa>aa</option>
<option value=bb>bb</option>
<option value=cc>cc</option>
</select>

jQuery : jQuery的:

$("#mySelect").val('bb');
$('.button').click(function(){

    $.ajax({
        type: "POST",
        url: "test.php",
        success: function(data){

               $('.select_class').val(data);

        }
    }); 

});

You can use jQuery val() method, but you can also use the basic javascript function and properties of the select (which have a better performance) 您可以使用jQuery val()方法,但也可以使用基本的javascript函数和select属性(具有更好的性能)

select.selectedIndex

is the current selected index, so you can select what you want by setting this propertie 是当前选择的索引,因此您可以通过设置此属性来选择所需的内容

select.options

is the array of options in your select 是您选择的选项数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM