Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  67] [ 5]  / answers: 1 / hits: 31706  / 10 Years ago, sun, july 20, 2014, 12:00:00

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>

More From » ajax

 Answers
6

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 :




[#70133] Friday, July 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubreeg

Total Points: 437
Total Questions: 102
Total Answers: 102

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;