切换案例JavaScript表单



我希望这不是重复的。我想以这种方式构建一个交互式web表单。在每个问题或选择之后,用户都会出现新的问题,因此在此之前,所有问题都隐藏在第一个问题旁边;我的第二个问题是我想要第二个,第三个。。回答取决于他们对上一个问题的回答。你知道我怎样才能用开关盒做到这一点吗。我将在这里举一个我想要的小例子:

因此,表单中出现的唯一问题是你住在哪里,如果用户选择法国,就会创建第二个下拉列表,要求选择法国城市,并且只显示法国城市,依此类推

<p>Where do you live</p>
<select name="country" id="country" required>
<option value="UK">UK</option>
<option value="UK">France</option>
</select>
<p>select the city in the uk</p>
<select name="town1 id="town1" required>
<option value="London">London</option>
<option value="Manchester">Manchester</option>
</select
<p>select the city in france</p>
<select name="town2 id="town2" required>
<option value="Paris">Paris</option>
<option value="St.Tropez">St.tropez</option>
</select>

谢谢你的帮助,Alex

试试这个
您不需要为每个国家/地区重复选择。只需设置与数据国家的相关性。

对于另一个问题,你可以做出同样的回答。为问题包装器设置具有适当值的数据属性,它们在表单更改时动态显示或隐藏。

// This listener makes dependency variants in select
document.getElementById('country').addEventListener('change', function() {
const selectedCountryValue = this.value;
document.getElementById('selectedCountry').innerText = this.children[this.selectedIndex].text;
const town = document.getElementById('town');
town.querySelectorAll('option').forEach(function(opt, i) {
opt.style.display = opt.dataset.country == selectedCountryValue ? 'block' : 'none';
if ((i == town.selectedIndex) && opt.dataset.country != selectedCountryValue) {
town.querySelectorAll(`option[data-country="${selectedCountryValue}"]`)[0].selected = true
}
});
})
document.getElementById('country').dispatchEvent(new Event('change'))
// This listener makes questions showed and required, if another questions answered appropriate answers
document.getElementById('dynamicForm').addEventListener('change', function() {
const form = this;
document.querySelectorAll('.question').forEach(function(question) {
let activeQuestion = true;
Object.keys(question.dataset).forEach(function(key) {
activeQuestion &= (question.dataset[key] == form.querySelector(`#${key}`).value);
})
question.style.display = (activeQuestion) ? 'block' : 'none'
question.querySelector('input, select').required = activeQuestion;
});
})

document.getElementById('dynamicForm').dispatchEvent(new Event('change'))
<form id="dynamicForm">
<p>Where do you live</p>
<select name="country" id="country" required>
<option value="UK">UK</option>
<option value="France">France</option>
</select>
<p>Select the city in the <span id="selectedCountry"></span></p>
<select name="town" id="town" required>
<option data-country="UK" value="London">London</option>
<option data-country="UK" value="Manchester">Manchester</option>
<option data-country="France" value="Paris">Paris</option>
<option data-country="France" value="St.Tropez">St.tropez</option>
</select>
<div class="question" data-country="France">
<p>Another one question if you live in France</p>
<input type="text" />
</div>
<div class="question" data-town="Paris">
<p>Another one question if you live in Paris</p>
<input type="text" />
</div>
</form>

最新更新