views:

1106

answers:

3

Hi friends,

I want to select an option in select tag through the value. - javascript

var selectbox=document.getElementById("Lstrtemplate");
var TemplateName=selectbox.options[selectbox.selectedIndex].text;

Now i am having the option text in TemplateName, using this i want to update an another select tag, which is having the same text..

But dont want to use index or id..

Want to achieve only by the value

Please help me

+1  A: 

Try it like this :

var TemplateName = selectbox.options[selectbox.selectedIndex].value;
Andreas Grech
+1  A: 

I'm not sure if I interpret your question correctly. You have two select elements and you want changes to one reflect in the other. I assume that they both have the same set of options and you need them synchronized.

If yes then:

var selectbox=document.getElementById("temp1");
var selectbox2=document.getElementById("temp2");
selectbox2.value = selectbox.value;

this keeps temp2 in sync with temp1, where temp1 and temp2 are the two select elements.

Vincent Ramdhanie
A: 

The sample above (selectobx2.value = selectbox.value) will correlate 2 select elements based on value, from your description I think you want to correlate 2 select elements based on the display value or text property.

Unfortunately there is no shortcut to do this and you need to enumerate the options yourself searching for the option whose text property matches the one you're looking for.

var selectbox=document.getElementById("Lstrtemplate");
var TemplateName=selectbox.options[selectbox.selectedIndex].text;

var select2 = document.getElementById("SecondSelect");
for (optionElem in select2.options)
    if (optionElem.text == TemplateName)
    {
        select2.value = optionElem.value;
        break;
    }
Peter Oehlert
@Peter: add a break when you have found the value. There is no need to go trough the whole list:if (optionElem.text == TemplateName) { select2.value = optionElem.value; break; }
some