Reputation: 1081
There is situation like this:
<select id="trollSelect">
<option value="PL">Troll</option>
<option value="EN">Troll</option>
<option value="JP">Troll</option>
</select>
I want to change $(#trollSelect option).text("NEW_VALUE")
in $(document).ready(function() {...}
- when page is ready.
The final effect should be like that:
<select id="trollSelect">
<option value="PL">Pan Troll</option>
<option value="EN">Mr Troll</option>
<option value="JP">Troll Sama</option>
</select>
I want not to use Server Side Script, it must be done in JQuery or JavaScript. Is this possible to do something like foreach(options)
?
UPDATE:
I would want to generate Text for options in this way:
function getTrollText(isoCode) // isoCode from option.val()
{
[...] // some magic, it does not matter
return result; // Here will be returned the text:
// "Pan Troll", "Mr Troll", or "Troll Sama"
}
Upvotes: 0
Views: 142
Reputation: 1081
$(document).ready(function() {
$('#trollSelect option').each(function(i,_){
$(this).text(getTrollText($(this).val()));
});
});
Maybe this way will be good.
Upvotes: 0
Reputation: 67217
Try,
$(document).ready(function() {
var newValues = ['Pan Troll','Mr Troll','Troll Sama'];
$('#trollSelect option').each(function(i,_){
$(this).text(newValues[i]);
});
});
Upvotes: 2
Reputation: 59292
Yes. Try this:
$(function () {
var arr = ['Pan Troll','Mr Troll','Troll Sama'];
$('#trollSelect option').text(function (index, value) {
return arr[index];
});
});
This uses the function callback overload of .text()
, which passes two parameters index, the actual index, which starts from 0 so it can be used to access the arr
values
Upvotes: 2
Reputation: 20646
Check this Demo
$(document).ready(function(){
var arr = ['Pan Troll','Mr Troll','Troll Sama'];
$('#trollSelect option').each(function(i){
console.log($(this).html(arr[i]));
});
});
OR
$(document).ready(function(){
var arr = ['Pan Troll','Mr Troll','Troll Sama'];
$.each($('#trollSelect option'),function(i){
console.log($(this).html(arr[i]));
});
});
Use .each() to iterate over the <option>
Upvotes: 2
Reputation: 82251
as you have not mentioned how the options are gonna appear i am storing them in array. then you can iterate over the option and set the html for each option by using options index to get new text from array :
$(function () {
var chngearr=['Pan Troll','Mr Troll','Troll Sama'];
$('#trollSelect option').each(function(){
$(this).html(chngearr[$(this).index()]);
});
});
Upvotes: 2