开发者

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜