Forum Moderators: open

Message Too Old, No Replies

Try to rename text in my options list

Options

         

aliUK

1:46 pm on Dec 31, 2008 (gmt 0)

10+ Year Member



Hi,

i'm still a js newbie and wondered if someone could help/point me in the right direction.
I'm trying to change some text that appears in a select list that is placed on my page. At the moment my list looks like this

1 - 1 of 4
row(s)2 - 2 of 4
3 - 3 of 4
4 - 4 of 4

My selected list is being generated dynamically by an HTML engine. In this example row 2 of 4 is the current value. What I want to do is replace the text in the select list to read as follows.

1 of 4
2 of 4
3 of 4
4 of 4

This is my js function at the moment which is reading the text from the select list but how do I replace the text. Perhaps there is also a better way to search and replace the "x - " part of the text:


function findChangeSelect(){
var optionItem = new Array();
var optionItem = document.getElementsByTagName('option');
//for each option tag in the select list
for (x in optionItem){
//only if the array value is a number
// Not sure why it reads some other values as I only have one select list
if (x > -1){
alert(optionItem[x].innerHTML);
//declare the text value
var optionText = optionItem[x].innerHTML;
if(optionText.indexOf(' - ') > 0){
var txtReplace = optionText.substr(0,optionText.indexOf(' - '));
var txtNew = optionText.substr(optionText.indexOf(' - '));
optionText = optionText.replace(txtReplace,txtNew);
}
}
}
}

Thanks in advanced.

coopster

9:50 pm on Dec 31, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Can you show us the html example for the select element and options? Example:
<select name="myname"> 
<option value="1">1 - 1 of 4</option>
<option value="2">2 - 2 of 4</option>
<option value="3">3 - 3 of 4</option>
<option value="4">4 - 4 of 4</option>
</select>

Fotiman

10:07 pm on Dec 31, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



An option element has a "text" property. Instead of changing the innerHTML, use the option's text attribute.

aliUK

8:37 am on Jan 1, 2009 (gmt 0)

10+ Year Member



Thanks Fotiman,

I was playing around with my js again. I found quiet a few things worng but have managed to egt it working thanks to your support

This is what I have ended up with


<script type="text/javascript">
function findChangeSelect(){
var optionItem = new Array();
var optionItem = document.getElementsByTagName('option');

for (x in optionItem){
if (x > -1){
//alert(optionItem[x].innerHTML);
var optionText = optionItem[x].innerHTML;
if(optionText.indexOf(' - ') > 0){
//var txtReplace = optionText.substring(0,optionText.indexOf(' - '));
var txtNew = optionText.substring(optionText.indexOf(' - ')+3);
//optionText = optionText.replace(txtReplace,txtNew);
optionItem[x].text = txtNew;
}
}
}
}

</script>

Happy New Year to all!