amirali shahinpour
amirali shahinpour

Reputation: 189

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.

<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. Let say that php responds me back "bb" then how can I change this select to be selected on bb??

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

does not work.

Upvotes: 0

Views: 152

Answers (4)

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

$('.button').click(function(){

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

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

        }
    }); 

});

Upvotes: 1

MatRt
MatRt

Reputation: 3534

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)

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

Upvotes: 1

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Add an identifier to your select element such as an ID, then you can just set the value with .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

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

Where phpResponseValue is the value returned from the AJAX response such as aa.

Upvotes: 2

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

HTML:

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

jQuery :

$("#mySelect").val('bb');

Upvotes: 1

Related Questions