Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value of Select option in Javascript

Is there any function to set value of a <select> tag option? I have an ajax response array and I want to put this array in a <select> tag.

This is my code :

$.ajax({
    type: "GET",
    url: "http://.......api/1/AbsenceType",
    dataType: "json", 
    success: function (data) {
        // It doesn't work
        var ind = document.getElementById('mySelect').selectedIndex;
        document.getElementById('mySelect').options.value="2";//
    }
})

And my select tag is :

<select id=mySelect name="mySelect" required="required" data-mini ="true" onchange="myFunction3();"/>
    <option id ="type" value=""></option>
</select>
like image 871
Sereen star Avatar asked Jul 20 '14 09:07

Sereen star


People also ask

How do you change the value of the Select option?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.

How do I set the default option in select?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do I get a dropdown selected value?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


1 Answers

I have an ajax response array and I want to put this array in a tag.

Why don't you just add the options from the array to the select, then set the selected value, like this :

Start with an empty select :

<select id="mySelect" name="mySelect">

</select>

Then use this function as a callback :

var callback = function (data) {

    // Get select
    var select = document.getElementById('mySelect');

    // Add options
    for (var i in data) {
        $(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
    }

    // Set selected value
    $(select).val(data[1]);
}

Demo :

http://jsfiddle.net/M52R9/

See :

  • Adding options to a select using Jquery/javascript
  • Set selected option of select box.
like image 126
user3856210 Avatar answered Oct 15 '22 18:10

user3856210