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>
4
  • what do you mean ? document.getElementById('mySelect').value="2"; Commented Jul 20, 2014 at 9:27
  • do you mean you want to change the value of the option tag? Commented Jul 20, 2014 at 9:30
  • 1
    i want to add value to option tag ,, it is empty and i want to fill it with the array from ajax response . Commented Jul 20, 2014 at 9:33
  • Use $("#type").attr("value", 2); however it just only assigns the value to 1 option tag that has the id "type", for multiple options, you would require that to generate as demonstrated in the example of Shail Commented Jul 20, 2014 at 9:42

3 Answers 3

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 :

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.