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>
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.
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.
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.
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With