Question

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")?

Was it helpful?

Solution 2

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.

OTHER TIPS

Try putting quotes around all of your HTML attributes, this is standard practice.

Also, in your find selector you should put quotes around clozefox_answer and id ( ['id'='clozefox_answer'] )

If that doesn't work, then try getting the value by calling $( this ).attr( 'value' );

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top