javascript - 在检查单选按钮的评论中发布答案

标签 javascript jquery html

我想以某种方式编写我的代码,以便一旦您选中正确的单选按钮(是/否),它就会连同问题一起显示在 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:

http://jsfiddle.net/gk05pkkh/3/

最佳答案

您应该在输入中使用“名称”而不是“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));
    }
}

http://jsfiddle.net/gk05pkkh/24/

关于javascript - 在检查单选按钮的评论中发布答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855803/

相关文章:

javascript - 如何从嵌套函数中检索值

javascript - jQuery 最接近(当元素具有多个类时最接近 hasClass)

javascript - 使用javascript访问ul中的li元素

html - 什么都没有时出现垂直滚动条

html - 如果 child 较小,则继承​​父宽度 - child 定位绝对

html - 如何使用 2 个类在 CSS 中选择标签

javascript - 更改 Vuetify 时间轴线的颜色

javascript - Mongo 会处理我的服务吗?

javascript - 使用 Cucumber/Capybara 测试执行 JavaScript

java - jsTree,刷新时需要展开所有节点