1

there are many examples out there of how to loop through Select Options, e.g.

Iterate through <select> options

but my problem is that I have to loop through an HTML string e.g. :

 var s = "<option value="0">OptA</option><option value="1">OptB</option><option value="2">OptC</option>"

How can I loop through each item please? the idea is that I have a string obtained from a dropdownlist.innerHTML, and an ID to find between all the options in the innerHTML:

GetValueFromHTML(iValueToFind,strHTML){
  $(strHTML).each(function () {
    var iTempValue = 
    var OptionText = 
    if  (iTempValue == iValueToFind){
      alert(OptionText );
      }
     })
}
aynber
  • 22,380
  • 8
  • 50
  • 63
Peter PitLock
  • 1,823
  • 7
  • 34
  • 71

3 Answers3

1

This seems to give the result you want, you were very close. Just needed the $(this).val() really:

function GetValueFromHTML(valueToFind ,html){
    $(html).each(function () {
        var val = $(this).val();
        if  (val == valueToFind){
            alert($(this).text());
        }
    });
}

http://jsfiddle.net/K2p9n/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
0
var s = "<option value="0">OptA</option><option value="1">OptB</option><option value="2">OptC</option>";
var selectElement = document.createElement('select');
selectElement.innerHTML = s;

From here on, you can use the examples you have seen that allow you to loop through the options in a select list.

Fenton
  • 241,084
  • 71
  • 387
  • 401
0

This would work:

function GetValueFromHTML(valueToFind ,html){
    alert ($('<select>' + html + '</select').find('[value=' + valueToFind + ']').text());
}
aquinas
  • 23,318
  • 5
  • 58
  • 81