views:

45

answers:

2

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

+1  A: 

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' );

Jacob Relkin
Certainly can't hurt! :)
thenduks
I have changed the relevant parts of the code as you said but still the same problem, $(this).val() is returning the option text instead of option value: listOfWords[i] = "<select id=\"clozefox_answer\"> <option value=\"wrongAnswer\">distractor</option>" listOfWords[i] += "<option value=t\"trueAnswer\">" + currentWord + "</option></select>";... $(doc).find("select[id='clozefox_answer']").each(function (index) { var selectedValue = $(this).val(); if (selectedValue == "trueAnswer") { numCorrectAnswer++; } });
Emre Sevinç
A: 

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.

Emre Sevinç