7

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>
Scott
  • 21,211
  • 8
  • 65
  • 72
Sereen star
  • 211
  • 2
  • 3
  • 8

3 Answers3

11

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 :

Community
  • 1
  • 1
user3856210
  • 270
  • 2
  • 12
1

try this...

<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>`
</select>

$("select").val("3");

visit live demo here: http://jsfiddle.net/y4B68/

thank you

Kalpesh Rajai
  • 2,040
  • 27
  • 39
0

Are you looking for something like that -

DEMO

You can add option like this -

$(function(){
$("#mySelect").html('<option value="2">2</option>');
});

Sorry i just missed that you are doing it in ajax callback. i have also updated in my demo.

you can also this too-

document.getElementById("mySelect").innerHTML = '<option value="2">2</option>';

Why don't you add new option instead of adding a value in option.

Shail Paras
  • 1,125
  • 1
  • 14
  • 34