我试图找出如何根据表单提交的值刷新div的内容。基本上,我有一个HTML表单:
<form method="post" id="diabetestool">
<table id="tooltable">
<tr>
<td>
<p>How old are you?</p>
</td>
<td>
<input type="radio" id="age1" name="age" value="0" checked>
<label for="age1">1-25</label>
</td>
<td>
<input type="radio" id="age2" name="age" value="5">
<label for="age2">26-40</label>
</td>
<td>
<input type="radio" id="age3" name="age" value="8">
<label for="age3">41-60</label>
</td>
<td>
<input type="radio" id="age4" name="age" value="10">
<label for="age4">60+</label>
</td>
</tr>
<tr>
<td colspan="5">
<button class="btn" type="button" name="submit" onclick="calculate()"><span>Calculate</span></button>
</td>
</tr>
</form>
这是它的一个简单版本..然后我有一个&#34;窗口&#34;我希望在表单中单击提交按钮时显示。
<div class="responsive-centered-box" id="resultWindow" style="display:none">
<p>sample text</p>
</div>
这是我的Javascript:
function calculate() {
let resultWindow = document.getElementById("resultWindow");
let i;
let age_Value, bmi_Value, family_Value, describe_Value;
for(i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked)
age_Value = document.getElementById('age' + i).value;
}
if (resultWindow.style.display == 'none') {
resultWindow.style.display = '';
console.log(age_Value);
}
}
它记录已检查的无线电选项的值,它也会使&#34;窗口&#34;可见,但它只适用于第一次点击..
我希望它能够像我点击按钮一样,它给我选中选项的值,但如果我选择另一个选项并再次点击该按钮,我想看到该值。
希望这是有道理的,感谢您的帮助!
答案 0 :(得分:3)
您的代码运行正常。您只需要更新输出显示,无论div最初是否被隐藏。
if (resultWindow.style.display == 'none') {
resultWindow.style.display = '';
console.log(age_Value); // take this out of this block
}
将其更改为:
if (resultWindow.style.display == 'none') {
resultWindow.style.display = '';
}
console.log(age_Value); // here it will work
答案 1 :(得分:1)
您的检查是否显示=='无',但当您再次执行功能时,您忘记重置样式。
function calculate() {
let resultWindow = document.getElementById("resultWindow");
resultWindow.style.display = 'none';
let age_Value, bmi_Value, family_Value, describe_Value;
for(let i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked)
age_Value = document.getElementById('age' + i).value;
}
if (resultWindow.style.display == 'none') {
resultWindow.style.display = '';
console.log(age_Value);
}
}
<form method="post" id="diabetestool">
<table id="tooltable">
<tr>
<td>
<p>How old are you?</p>
</td>
<td>
<input type="radio" id="age1" name="age" value="0" checked>
<label for="age1">1-25</label>
</td>
<td>
<input type="radio" id="age2" name="age" value="5">
<label for="age2">26-40</label>
</td>
<td>
<input type="radio" id="age3" name="age" value="8">
<label for="age3">41-60</label>
</td>
<td>
<input type="radio" id="age4" name="age" value="10">
<label for="age4">60+</label>
</td>
</tr>
<tr>
<td colspan="5">
<button class="btn" type="button" name="submit" onclick="calculate()"><span>Calculate</span></button>
</td>
</tr>
</form>
<div class="responsive-centered-box" id="resultWindow" style="display:none">
<p>sample text</p>
</div>