views:

73

answers:

2

I have some html that creates a dropdown list. The list has text values and text that is displayed to the user. I save some XML based on the “values” the user selects. At some other point in time I need to parse the XML and display the original text but not in the original list. At this point I only have the “value” from the list and not its display text. At first I was going to use a switch statement to get the display text but then had the idea of using the information that is held in the list. Is it possible to use a bit of javascript to use the value I have to look-up the display version on the list? If so, can someone supply a code snippet? I’ve tried different ways but so far drawn a blank. Shown below is a sample of the html that makes up the list.

'<select id="ifmgr_tr_Field">' +
'<option value="DeviceId">Device ID</option>' +
'<option value="DeviceMac">Device MAC</option>' +
'<option value="DeviceType">Device Type</option' +
'</select>';

Let’s say I have a value of “DeviceMac”, what I want from this list is “Device MAC”. Remember that I don’t want to use the list to display the value at this point.

EDIT

I could do this but it feels a bit dirty.

var item = $('#ifmgr_tr_Field')[0] ;
item.value = field; // field would be the value I have, EG “DeviceMac”
var text = item.options[item.selectedIndex].text; // This will give me “Device MAC” which is what I want.
A: 

I'm not sure EXACTLY what you want to do in the JS function, but you'll need to add the onchange attribute to your select item. It will need to point to your JS function, and pass the value when changed.

'<select onchange="doTheFunction(this.value);" id="ifmgr_tr_Field">' + ...

Then in your JS Code:

function doTheFunction(val){

   //val will hold the newly selcted value

   if (val=="DeviceId"){
      //do something for DeviceId

   } else if (val=="DeviceMac"){
      //do something for DeviceMac

   } else if (val=="DeviceType"){
      //do something for DeviceType

   }
}
Dutchie432
I probably didn’t describe the problem very well. I don’t want to have an “if” statement as I wanted the List to provide me with what I want. I have edited my question with a snippet of code that works but changes the list visually as it provides me with the answer I need. Can I do something similar (using the list as a look-up) but without changing the display?
Retrocoder
+1  A: 

I hope this might help. Well it still has a if condition. But as you said the value in the ListBox does not change. It uses list as a look-up and finds the option where the Text of option is "Device MAC" for example. emm... well i used jQuery cause it have a better loop(each) function than traditional javascript.

    $('#ifmgr_tr_Field option').each(function () {
        var option = this;
        if(option.text == 'Device MAC')
        alert(option.text + " Value : " + option.value);
    }); 
J Sinh
Thanks, that works a treat.
Retrocoder