将多个单选按钮值存储在一个数组中 Javascript
Store multiple radio button values in an array Javascript
我想将我的测试答案存储在 javascript 中的数组中。我用 for 循环创建了 50 个问题,用户可以在 4 个单选按钮(答案)之间进行选择。我如何将这些答案存储在数组中?
我的问题卡
<% for(var i = 0; i < test.questions.length; i++){%>
<br>
<div class="card">
<div class="card-header">
<%= test.questions[i].question%></h5>
</div>
<ul class="list-group list-group-flush" style="padding: 10px;">
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="a"> <%= test.answers[0].answer%></li>
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="b"> <%= test.answers[1].answer%></li>
<li class="list-group-item"> <input type="radio" name="one+<%=i%>" value="c"> <%= test.answers[2].answer%></li>
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="d"> <%= test.answers[3].answer%></li>
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="e"> <%= test.answers[4].answer%></li>
</ul>
</div>
</div>
<%}%>
我尝试了什么:
<script>
var arr = []
document.getElementById("confirm").addEventListener("click", function() {
for (let index = 0; index < 51; index++) {
var buttonName = "one" + index
var buttChecked = document.querySelector('[name=buttonName]:checked')
if (buttChecked != null) {
arr.push(buttChecked.value)
}
console.log(arr)
}
})
</script>
只需循环遍历包含单选按钮组名称的数组,获取该组中所选按钮的值并添加到数组中:
// Store the names of the radio button sets
let names = ["one","two","three"]
let results = [];
document.querySelector("button").addEventListener("click", function(event){
results = names.map(function(el){
return document.querySelector("input[name='" + el + "']:checked").value;
});
console.log(results);
});
<div class="question">
<input type="radio" name="one" value="Choice A">Something |
<input type="radio" name="one" value="Choice B">Something |
<input type="radio" name="one" value="Choice C">Something
</div>
<div class="question">
<input type="radio" name="two" value="Choice A">Something |
<input type="radio" name="two" value="Choice B">Something |
<input type="radio" name="two" value="Choice C">Something
</div>
<div class="question">
<input type="radio" name="three" value="Choice A">Something |
<input type="radio" name="three" value="Choice B">Something |
<input type="radio" name="three" value="Choice C">Something
</div>
<br>
<button>Collect Answers</button>
使用 Handlebars JS,您可以设置 question/answer 数据结构并在问题之间导航,预选答案。
const randomSort = arr => arr.sort(() => 0.5 - Math.random());
const mod = (n, m) => ((n % m) + m) % m;
const bump = (count, index, amount) => mod(index + amount, count);
// Handlebars helpers
Handlebars.registerHelper({
ifEquals: function(arg1, arg2, options) {
return arg1 === arg2 ? options.fn(this) : options.inverse(this);
},
randomEach: function(array, opts) {
if (opts.data) data = Handlebars.createFrame(opts.data);
return randomSort(array).map((e, i) => {
if (data) data.index = i;
return opts.fn(e, { data });
}).join('');
}
});
const compileTemplate = (selector) =>
Handlebars.compile(document.querySelector(selector).innerHTML);
const questions = [{
prompt: "Which fruit is yellow?",
answers: [ "Apple", "Banana", "Cantaloupe", "Date" ],
answer: "Banana"
}, {
prompt: "Which vegetable is red?",
answers: [ "Carrot", "Pea", "Potato", "Tomato" ],
answer: "Tomato"
}];
// Buttons
const prevBtn = document.querySelector('#controls > .prev-btn');
const nextBtn = document.querySelector('#controls > .next-btn');
const showBtn = document.querySelector('#controls > .show-btn');
let currQuestion = 0;
let answers = {};
const main = () => {
rerender();
prevBtn.addEventListener('click', handlePrev);
nextBtn.addEventListener('click', handleNext);
showBtn.addEventListener('click', handleShow);
};
const updateAnswers = (button) => {
const form = button.closest('form');
const value = form.elements.answer.value;
answers[currQuestion] = value;
}
// Templates
const questionTemplate = compileTemplate('#question-template');
const infoTemplate = compileTemplate('#info-template');
const answersTemplate = compileTemplate('#answers-template');
// Rendering contexts
const questionEl = document.querySelector('#question');
const infoEl = document.querySelector('#info');
const answersEl = document.querySelector('#answers');
const navigateQuestion = (amount) => {
currQuestion = bump(questions.length, currQuestion, amount);
};
const handlePrev = () => {
navigateQuestion(-1);
rerender();
};
const handleNext = () => {
navigateQuestion(-1);
rerender();
};
const handleShow = () => {
const answerList = questions.map((question, index) => answers[index]);
answersEl.innerHTML = answersTemplate(answerList);
};
const renderQuestion = (question) => {
questionEl.innerHTML = questionTemplate(question);
infoEl.innerHTML = infoTemplate({
page: currQuestion + 1,
count: questions.length
});
};
const rerender = () =>
renderQuestion(questions[currQuestion]);
main();
.answer-field {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script id="question-template" type="text/x-handlebars-template">
<h2>{{prompt}}</h2>
<form onsubmit="return false">
{{#randomEach answers}}
<div class="answer-field">
<input
type="radio"
id="answer-{{@index}}"
name="answer"
value="{{.}}"
{{#ifEquals . ../answer}}checked{{/ifEquals}}
>
<label for="answer-{{@index}}">{{.}}</label>
</div>
{{/randomEach}}
<br />
<button onclick="updateAnswers(this)">Submit</button>
</form>
</script>
<script id="info-template" type="text/x-handlebars-template">
<p>Question {{page}} of {{count}}</p>
</script>
<script id="answers-template" type="text/x-handlebars-template">
<ol>
{{#each .}}
<li>{{.}}</li>
{{/each}}
</ol>
</script>
<div id="question"></div>
<div id="info"></div>
<div id="controls">
<button class="prev-btn">Prev</button>
<button class="show-btn">Show Answers</button>
<button class="next-btn">Next</button>
</div>
<h2>Submitted Answers</h2>
<div id="answers"></div>
我想将我的测试答案存储在 javascript 中的数组中。我用 for 循环创建了 50 个问题,用户可以在 4 个单选按钮(答案)之间进行选择。我如何将这些答案存储在数组中?
我的问题卡
<% for(var i = 0; i < test.questions.length; i++){%>
<br>
<div class="card">
<div class="card-header">
<%= test.questions[i].question%></h5>
</div>
<ul class="list-group list-group-flush" style="padding: 10px;">
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="a"> <%= test.answers[0].answer%></li>
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="b"> <%= test.answers[1].answer%></li>
<li class="list-group-item"> <input type="radio" name="one+<%=i%>" value="c"> <%= test.answers[2].answer%></li>
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="d"> <%= test.answers[3].answer%></li>
<li class="list-group-item"><input type="radio" name="one+<%=i%>" value="e"> <%= test.answers[4].answer%></li>
</ul>
</div>
</div>
<%}%>
我尝试了什么:
<script>
var arr = []
document.getElementById("confirm").addEventListener("click", function() {
for (let index = 0; index < 51; index++) {
var buttonName = "one" + index
var buttChecked = document.querySelector('[name=buttonName]:checked')
if (buttChecked != null) {
arr.push(buttChecked.value)
}
console.log(arr)
}
})
</script>
只需循环遍历包含单选按钮组名称的数组,获取该组中所选按钮的值并添加到数组中:
// Store the names of the radio button sets
let names = ["one","two","three"]
let results = [];
document.querySelector("button").addEventListener("click", function(event){
results = names.map(function(el){
return document.querySelector("input[name='" + el + "']:checked").value;
});
console.log(results);
});
<div class="question">
<input type="radio" name="one" value="Choice A">Something |
<input type="radio" name="one" value="Choice B">Something |
<input type="radio" name="one" value="Choice C">Something
</div>
<div class="question">
<input type="radio" name="two" value="Choice A">Something |
<input type="radio" name="two" value="Choice B">Something |
<input type="radio" name="two" value="Choice C">Something
</div>
<div class="question">
<input type="radio" name="three" value="Choice A">Something |
<input type="radio" name="three" value="Choice B">Something |
<input type="radio" name="three" value="Choice C">Something
</div>
<br>
<button>Collect Answers</button>
使用 Handlebars JS,您可以设置 question/answer 数据结构并在问题之间导航,预选答案。
const randomSort = arr => arr.sort(() => 0.5 - Math.random());
const mod = (n, m) => ((n % m) + m) % m;
const bump = (count, index, amount) => mod(index + amount, count);
// Handlebars helpers
Handlebars.registerHelper({
ifEquals: function(arg1, arg2, options) {
return arg1 === arg2 ? options.fn(this) : options.inverse(this);
},
randomEach: function(array, opts) {
if (opts.data) data = Handlebars.createFrame(opts.data);
return randomSort(array).map((e, i) => {
if (data) data.index = i;
return opts.fn(e, { data });
}).join('');
}
});
const compileTemplate = (selector) =>
Handlebars.compile(document.querySelector(selector).innerHTML);
const questions = [{
prompt: "Which fruit is yellow?",
answers: [ "Apple", "Banana", "Cantaloupe", "Date" ],
answer: "Banana"
}, {
prompt: "Which vegetable is red?",
answers: [ "Carrot", "Pea", "Potato", "Tomato" ],
answer: "Tomato"
}];
// Buttons
const prevBtn = document.querySelector('#controls > .prev-btn');
const nextBtn = document.querySelector('#controls > .next-btn');
const showBtn = document.querySelector('#controls > .show-btn');
let currQuestion = 0;
let answers = {};
const main = () => {
rerender();
prevBtn.addEventListener('click', handlePrev);
nextBtn.addEventListener('click', handleNext);
showBtn.addEventListener('click', handleShow);
};
const updateAnswers = (button) => {
const form = button.closest('form');
const value = form.elements.answer.value;
answers[currQuestion] = value;
}
// Templates
const questionTemplate = compileTemplate('#question-template');
const infoTemplate = compileTemplate('#info-template');
const answersTemplate = compileTemplate('#answers-template');
// Rendering contexts
const questionEl = document.querySelector('#question');
const infoEl = document.querySelector('#info');
const answersEl = document.querySelector('#answers');
const navigateQuestion = (amount) => {
currQuestion = bump(questions.length, currQuestion, amount);
};
const handlePrev = () => {
navigateQuestion(-1);
rerender();
};
const handleNext = () => {
navigateQuestion(-1);
rerender();
};
const handleShow = () => {
const answerList = questions.map((question, index) => answers[index]);
answersEl.innerHTML = answersTemplate(answerList);
};
const renderQuestion = (question) => {
questionEl.innerHTML = questionTemplate(question);
infoEl.innerHTML = infoTemplate({
page: currQuestion + 1,
count: questions.length
});
};
const rerender = () =>
renderQuestion(questions[currQuestion]);
main();
.answer-field {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script id="question-template" type="text/x-handlebars-template">
<h2>{{prompt}}</h2>
<form onsubmit="return false">
{{#randomEach answers}}
<div class="answer-field">
<input
type="radio"
id="answer-{{@index}}"
name="answer"
value="{{.}}"
{{#ifEquals . ../answer}}checked{{/ifEquals}}
>
<label for="answer-{{@index}}">{{.}}</label>
</div>
{{/randomEach}}
<br />
<button onclick="updateAnswers(this)">Submit</button>
</form>
</script>
<script id="info-template" type="text/x-handlebars-template">
<p>Question {{page}} of {{count}}</p>
</script>
<script id="answers-template" type="text/x-handlebars-template">
<ol>
{{#each .}}
<li>{{.}}</li>
{{/each}}
</ol>
</script>
<div id="question"></div>
<div id="info"></div>
<div id="controls">
<button class="prev-btn">Prev</button>
<button class="show-btn">Show Answers</button>
<button class="next-btn">Next</button>
</div>
<h2>Submitted Answers</h2>
<div id="answers"></div>