这是我之前关于下拉菜单的问题的跟进:list options
我以前没有意识到这一点,但除了下拉菜单外,还有几个单选按钮,我想要获取单选按钮的文本,值和标签。
var html = '<table cellpadding=2 cellspacing=2 class="table table-striped"><tr><td class=registration-form>Is the patient enrolled in a VDOT research protocol?*<td><span id=cphBody_surveyControll_surveyWizard_S0100100 class="radio inline control-group" maintainscrollpositiononpostback=true><input id=cphBody_surveyControll_surveyWizard_S0100100_0 type=radio name=ctl00$cphBody$surveyControll$surveyWizard$S0100100 value=1 checked><label for=cphBody_surveyControll_surveyWizard_S0100100_0>Yes </label><input id=cphBody_surveyControll_surveyWizard_S0100100_1 type=radio name=ctl00$cphBody$surveyControll$surveyWizard$S0100100 value=0 onclick="setTimeout('__doPostBack(\'ctl00$cphBody$surveyControll$surveyWizard$S0100100$1\',\'\')', 0)"><label for=cphBody_surveyControll_surveyWizard_S0100100_1>No</label></span> <span id=cphBody_surveyControll_surveyWizard_rfvS0100100 class=text-error style=display:none>required</span><tr id=cphBody_surveyControll_surveyWizard_ShowS0100200><td class=registration-form>Informed Consent signed?*<td><span id=cphBody_surveyControll_surveyWizard_S0100200 class="radio inline control-group"><input id=cphBody_surveyControll_surveyWizard_S0100200_0 type=radio name=ctl00$cphBody$surveyControll$surveyWizard$S0100200 value=1 checked><label for=cphBody_surveyControll_surveyWizard_S0100200_0>Yes  </label><input id=cphBody_surveyControll_surveyWizard_S0100200_1 type=radio name=ctl00$cphBody$surveyControll$surveyWizard$S0100200 value="0"><label for=cphBody_surveyControll_surveyWizard_S0100200_1>No</label></span> <span id=cphBody_surveyControll_surveyWizard_rfvS0100200 class=text-error style=display:none>required</span></table>';
$(function () {
var tmpHTML = $(html);
var vals = [];
//get all existing SELECT menus
tmpHTML.find("select").each(function (index, itm) {
var opts = [];
//loop through each of the menu's options
$(this).find(":radio").each(function (i, opt) {
if (opt.text !== '') {
opts.push({
value: opt.val,
text: opt.text
});
}
});
//push the menu along with its options into an array
vals.push({
id: itm.id,
options: opts
});
});
console.log(vals);
});
在此处更改代码:DEMO并插入HTML(下方)作为var html
,并将两个finds
更改为span
和{{1}给了我所有未定义的数组
label
答案 0 :(得分:0)
根据this
中的单选按钮,您可以使用this.value
或$(this).val()
获取其值。您可以通过以下方式获取相关标签的文本:
$(this).closest("label").add($("label[for='" + this.id + "']")).text()
这显示了如何在数组中获取所有这些内容:
$(function () {
var tmpHTML = $(html);
var vals = [];
//get all existing SELECT menus
tmpHTML.find(":radio").each(function () {
vals.push({
value: this.value,
text: $(this).closest("label").add($("label[for='" + this.id + "']")).text()
});
});
console.log(vals);
});