[英]How to retrieve the value of the selected option from a dynamically created select in a table
I am dynamically creating a dropdown list in a table and want to retrieve the value of the selected item.我正在表中动态创建一个下拉列表,并希望检索所选项目的值。 I can get the value of other elements (eg, input);我可以获取其他元素的值(例如,输入); however the dropdown has me stumped.然而下拉菜单让我难住了。 In the below code the startDate is correct however parRating is always 1 (the first value in the select).在下面的代码中,startDate 是正确的,但是 parRating 始终为 1(选择中的第一个值)。
Note: I want the value (parIdArray) not the val (parRatingArray).注意:我想要值 (parIdArray) 而不是 val (parRatingArray)。
HTML for creating:用于创建的 HTML:
html += "<td style='width : 1%; white-space: nowrap;'><select name='parRating'>"
for (let i = 0; i <= paraArray; i++) {
if (this.parRating == parRatingArray[i]) {
// set the current option to this.parRating
html += "<option selected name='parRatingOption' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>"
}else {
html += "<option name='parRatingOption' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>"
}
};
html += "</select></td>";
if (this.patparStartDate == null) {
html += "<td style='width : 1%; white-space: nowrap;'><input type='date' name='startDate' value=''></td>";
}else {
html += "<td style='width : 1%; white-space: nowrap;'><input type='date' name='startDate' value='" + this.patparStartDate + "'></td>";
}
HTML to retrieve values:检索值的 HTML:
var parRating = $(this).parents('tr:first').find('option[name="parRatingOption"]').value;
alert("parRating: " + parRating);//always 1
var startDate = $(this).parents('tr:first').find('input[name="startDate"]').val();
You just need to target the option selected in your code above using the jQuery :selected selector:您只需要使用 jQuery :selected选择器将上面代码中选择的选项作为目标:
Also you need to use .val()
to get the option value not the value
attribute in jQuery您还需要使用.val()
来获取选项值而不是 jQuery 中的value
属性
Try this code below:试试下面的代码:
var parRating = $(this).parents('tr:first').find('option[name="parRatingOption"]:selected').val();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.