我想迭代一组动态生成的单选按钮并获取其标签,但是当我尝试打印它们的值时,没有任何内容出现,请参阅此脚本演示以获取示例http://jsfiddle.net/HaBhk/20/,这里是我生成的html按钮将会
<div data-role="content">
<div data-role="collapsible" data-inset="true">
<h1>AddVote</h1>
<div data-role="fieldcontain" >
<input type="text" name="name" id="question" value="" /><br>
<div data-role="controlgroup" data-type="horizontal" >
<label for="name"><a href="" id="AddButton" data-role="button"
data-icon="plus">Add</a><a href="" id="RemoveButton" data-role="button"
data- icon="delete">Delete</a>
</label>
<input type="text" name="option" id="option" value="" /><br>
</div>
<div data-role="fieldcontain">
<form name="OptionsForm" id="InputForm" method="get">
<div id="after" data-role="controlgroup">
/////Generated radio buttons goes here
</div>
</form>
</div>
<a href="#approve" id="publishButton" data-role="button"
data-inline="true"data-transition="flip">Preview</a>
</div><!-- /content -->
下面是我获取单选按钮值的脚本:
$('#publishButton').click(function(){
var result
var y=document.getElementById('question').value
var form='<Question value=' + y + '/>'+'<br>'
alert(form);
$('input:radio').each(function() {
var value=$('input:radio').val()
'<option value='+value + '/>'+'<br>'
alert(result);
});
答案 0 :(得分:2)
以下是一些示例代码,它将返回无线电选项的相关标签。
var labels = [];
$('input:radio').each(function(){
labels.push($('label[for='+$(this).attr('id')+']').text());
});
alert(labels);
答案 1 :(得分:1)
试试这个:http://jsfiddle.net/HaBhk/24/
<input type="text" name="option" id="option" value="" /><br>
<div id="AddButton" data-role="button" data-inline="true">Add</div>
<div id="RemoveButton" data-role="button" data-inline="true">remove</div>
<div id="publishButton" data-role="button" data-inline="true">publish</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup"><legend>Choose an Option:</legend><br><br>
<div id="after">
</div>
</fieldset>
</div>
<script type="text/javascript">
function createRadioElement(elem, label, checked) {
var id = 'option1_' + label;
$('#after').append($('<div><input type="radio" name="option1" id="'+id+ '" value="1"/><label for="' + id + '">'+label + '</label></div>'));
}
$('#AddButton').click(function() {
var x = document.getElementById('option').value;
createRadioElement(this, $('#option').val());
});
$('#RemoveButton').click(function() {
$('#after').children().children("input[checked='checked']").parent().remove();
});
$('#publishButton').click(function() {
var result;
$('#after input:radio').each(function() { // only radio buttons in #after
var value = $(this).next('label').html();
alert(value);
});
});
</script>
答案 2 :(得分:1)
$('#publish').click(function () {
var labs = $(':radio + label'),
alertString =[];
for (var i = 0, labLen = labs.length; i < labLen; i += 1) {
alertString[i] = labs[i].id;
};
alert(alertString.join("\n"));
});