我想以某种方式编写我的代码,以便一旦您选中正确的单选按钮(是/否),它就会连同问题一起显示在 textarea
中。如果选中了 yes
单选按钮。我希望 yes
显示在 textarea
中,并带有正确的问题,例如 问题 1
,如果选中 no
单选按钮,我希望 no
显示在 textarea
中。这是我现在拥有的:
HTML:
Question 1 Yes<input id='chk1' value="yes" type='radio' />No<input name='chk3' value="no" type='checkbox' /><br />
Question 2 Yes<input id='chk2' value="yes" type='radio' />No<input name='chk3' value="no" type='checkbox' /><br />
Question 3 Yes<input id='chk3' value="yes" type='radio' />No<input name='chk3' value="no" type='checkbox' /><br />
Other comments<textarea id='comment'></textarea><br /><input type=submit name=submit value='Post' />
JQuery:
$('#chk1').change(function(){
$('#comment').text("Question 1:" + "");
});
$('#chk2').change(function(){
$('#comment').text("Question 1:" + "");
});
$('#chk3').change(function(){
$('#comment').text("Question 1:" + "");
});
JSFiddle:
最佳答案
您应该在输入中使用“名称”而不是“id”,以便共享它们。
HTML:
Question 1 Yes<input name='chk1' value="yes" type='radio' />No<input name='chk1' value="no" type='radio' /><br />
Question 2 Yes<input name='chk2' value="yes" type='radio' />No<input name='chk2' value="no" type='radio' /><br />
Question 3 Yes<input name='chk3' value="yes" type='radio' />No<input name='chk3' value="no" type='radio' /><br />
Other comments<textarea id='comment'></textarea><br /><input type=submit name=submit value='Post' />
JQuery:
$('input[name="chk1"]').change(function(){
checkQuestion("Question 1", this.value);
});
$('input[name="chk2"]').change(function(){
checkQuestion("Question 2", this.value);
});
$('input[name="chk3"]').change(function(){
checkQuestion("Question 3", this.value);
});
function checkQuestion(text, value) {
if ($('#comment').text().indexOf(text)<0)
$('#comment').text($('#comment').text() + text + ":" + value + "\n");
else {
var oldValue = 'yes';
if (value==='yes') oldValue = 'no';
$('#comment').text($('#comment').text().replace(text + ":" + oldValue, text + ":" + value));
}
}
关于javascript - 在检查单选按钮的评论中发布答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855803/