Reputation: 179
sorry guys, previously I didn't mention the my dropdown list is made with bootstrap. based on @rps suggestion I asked to my colleague(who is made template) he said it's made with bootstrap.
I am putting basic html dropdown code,so I think you guys can understand How bootstrap code will be.
html code:
<select name="primary" class="select-block" id="select_alert">
<option "selected">Choose Alert T</option>
<option value="T1">T1</option>
<option value="T2">T2</option>
<option value="T3">T3</option>
<option value="T4">T4</option>
</select>
Initially i am getting the select menu in the following way.
for my conformation,I am finding the menu value in the following way.
i/p: document.getElementById('select_alert').value
o/p: "choose Alert T"
Now using javascript or jquery, I want to change select option in the follwoing way.For this I tried the below it's not working
document.getElementById('select_alert').value="T1";
Again If I check the value of select menu,it should be "T1".
Thanks
Upvotes: 2
Views: 4002
Reputation: 585
Try to do it this way :
$('#select_alert').val("T3");
$("#select_alert").selectmenu();
$("#select_alert").selectmenu("refresh");
Upvotes: 0
Reputation: 1338
without jquery you can use
document.getElementById('select_alert').selectedIndex = 1
if you want to find out the option index by given value try this
var sel = document.getElementById('select_alert'),
selopt = sel.options,
searchidx;
//alert(selopt[sel.selectedIndex].value);
//sel.selectedIndex = 1;
//alert(selopt[sel.selectedIndex].value);
//alert(sel.value)
// search for the index
searchidx = getoptidx(selopt, "T3");
if (searchidx !== false) {
sel.selectedIndex = searchidx;
alert(selopt[sel.selectedIndex].value);
} else {
alert("index not found")
}
/**
* returns the index of a value
* @todo optimize search?
*/
function getoptidx(opts, searchterm) {
for (var i in opts) {
if (opts[i].text === searchterm) return i;
}
return false;
}
the fiddle: http://jsfiddle.net/uzqZA/6/
Upvotes: 0
Reputation: 253308
My reading of the question is ambiguous, but if you're trying to set the value, or set the selected-option, to T1
:
$('#select_alert option[value="T1"]').prop('selected',true);
If you're trying to retrieve the value of the selected option:
$('#select_alert option:selected').val();
Upvotes: 1
Reputation: 3329
you can try this
// Get the value from a dropdown select
$( "#select_alert option:selected").val();
$( "#select_alert option:selected" ).text();
Upvotes: 1
Reputation: 2500
use as follows :
$('#select_alert').val('T1'); // in jquery
also your javascript code is correct, there must be some other error on the page.
Upvotes: 0