我很难显示所选单选按钮的值。当我单击问题1时,结果1应该显示在控制台上,但是我获得了单选按钮的所有值。有人可以帮我吗?谢谢
html
int main(int argc, const char * argv[]) {
@autoreleasepool
{
NSLog(@"Hello, World!");
for ( long i = 0; i < 1000000; i ++ )
{
// Direct ...
NSString * s = [NSString stringWithFormat:@"%ld", i ];
}
NSLog(@"1");
for ( long i = 0; i < 1000000; i ++ )
{
// Indirect via NSNumber ...
NSString * s = @(i).stringValue;
}
NSLog(@"2");
}
return 0;
}
JavaScript
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1">
<label>Question 2</label>
<input type="radio" class="question" value="2">
<label>Question 3</label>
<input type="radio" class="question" value="3">
<button type="submit">Submit</button>
</form>
答案 0 :(得分:1)
您可以检查是否已使用question.checked
进行了检查。
function answers(event)
{
var q = document.querySelectorAll('.question');
[...q].forEach(question =>{
if(question.checked){
console.log(question.value);
}
});
event.preventDefault();
}
您可能还想为所有收音机添加名称,因为收音机的想法是一次只能勾选其中一个。 name
为您做到了:
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1" name="question">
<label>Question 2</label>
<input type="radio" class="question" value="2" name="question">
<label>Question 3</label>
<input type="radio" class="question" value="3" name="question">
<button type="submit">Submit</button>
</form>
答案 1 :(得分:1)
而不是在循环内检查checked
属性。您可以使用:checked伪类来仅选择选中的无线电。
function answers(event)
{
var q = document.querySelectorAll('.question:checked');
[...q].forEach(question =>{
console.log(question.value);
});
event.preventDefault();
}
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1" name="question">
<label>Question 2</label>
<input type="radio" class="question" value="2" name="question">
<label>Question 3</label>
<input type="radio" class="question" value="3" name="question">
<button type="submit">Submit</button>
</form>
还要注意使用name属性对单选按钮进行分组。