Search code examples
jqueryselectfirefox-addonfirefox-addon-sdk

Getting the value of a select list using jQuery


This is a problem I face while using jQuery within Firefox Jetpack. In my Jetpack code I'm dynamically creating some SELECT boxes with options and their respective values:

...
listOfWords[i] = "<select id=clozefox_answer> <option
value=wrongAnswer>distractor</option>"
listOfWords[i] += "<option value=trueAnswer>" + currentWord +
"</option></select>"
...
textStr = listOfWords.join(" ");
$(this).html(textStr);

This works fine. Now after user makes some selections using the pull-down select lists on the page and clicks on the Calculate Score button I run a function to traverse the SELECT boxes and get their selected values:

$(doc).find("select[id=clozefox_answer]").each(function (index) {
   var selectedValue = $(this).val();

   if (selectedValue == "trueAnswer") {
       numCorrectAnswer++;
   }
});

Even though the above code correctly matched my dynamically created SELECTs, $(this).val() does NOT return the option value but the option text (e.g. "distractor" or whatever the variable currentWord included). How can I get the option value (e.g. "trueAnswer" or "wrongAnswer")?


Solution

  • The following code does what I expect:

    var selectedValue = $(this).attr("value");
    

    But I still don't know why

    var selectedValue = $(this).val();
    

    does not work as expected. Anyway, I have solved my problem for now.