1

I get a HTML string like this. I want to get the selected value, which, in this case is AN:

<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT>

which when formatted looks like this:

<SELECT id=ddl_Freq name=ddl_Freq>
    <OPTION selected value=AN>Annually</OPTION> 
    <OPTION value=BM>Bi-Monthly</OPTION> 
    <OPTION value=MO>Monthly</OPTION>
    <OPTION value=OT>One Time</OPTION> 
    <OPTION value=QT>Quarterly</OPTION> 
    <OPTION value=WE>Weekly</OPTION>
</SELECT>

I tried these two approaches, but I wasn't successful.

Approach 1: JavaScript

DdlHtml = document.createElement('select');
DdlHtml.innerHTML = RawDdlString;
item = DdlHtml.options[DdlHtml.selectedIndex].value;

This fails because the string already contains <SELECT> and </SELECT> tags.

Approach 2: jQuery

DdlHtml2 = $.parseHTML(RawDdlString);
item = DdlHtml2.options[DdlHtml2.selectedIndex].value;

This also didn't work as DdlHtml2.options is undefined.

How do I parse this string which contains HTML for a dropdownlist in either Javascript or jQuery?

3 Answers 3

3

Wrap the string in a jQuery selector:

$(function() {
    var $select = $("<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT");
   console.log($select.val()); 
});

Here is an example fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Using jQuery

$('#ddl_Freq').val()

Comments

0

without jQuery,

<SELECT id=ddl_Freq name=ddl_Freq>
    <OPTION selected value=AN>Annually</OPTION> 
    <OPTION value=BM>Bi-Monthly</OPTION> 
    <OPTION value=MO>Monthly</OPTION>
    <OPTION value=OT>One Time</OPTION> 
    <OPTION value=QT>Quarterly</OPTION> 
    <OPTION value=WE>Weekly</OPTION>
</SELECT>

var x = document.getElementById("ddl_Freq");
x.options[x.selectedIndex].value;



Output:
    "AN"

link to jsbin snippet:

http://jsbin.com/omuxow/1/edit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.