我正在尝试为选择下拉菜单创建一个后续字段。
例如,在第一个下拉菜单中,我有("是"=> 1,"否"=> 2,"无"=> 3)。我希望之后的字段在我点击后更改,选择其中一个选项。例如:如果我选择"是",则以下字段将是"选择"下拉菜单,对于"否",它将是一个文本区域,对于任何内容,它将是"什么都没有"。
我为自己尝试了一些代码,但没有用,因为我不知道如何在选择某些内容后立即更新以下字段。 我尝试了这样的事情:
if (select == 1) {
echo "$select2";
} else if (select == 2) {
echo "<input type='text' name='textarea1'/>";
}
但是我不知道如何使页面更新字段...
请帮助我
谢谢
这个想法是,你想使用JavaScript来显示/隐藏问题,这取决于前一个问题的答案。这称为决策树。如果你谷歌它,他们会来的。您可以找到一堆示例和库,它们为您完成了大部分繁重的工作。
如果你想建立自己的,这里有一个非常简单的方法。这不是一个可扩展的解决方案,但它应该让您了解它应该如何工作的基本概念。
.HTML
<label>Do you want this?
<select name="choices" id="choices">
<option value="1">Yes</option>
<option value="2">No</option>
<option value="3" selected>Nothing</option>
</select>
</label>
<div id="choices-followup">
<div id="followup1">
<label>
How bad do you want this?
<select>
<option>Give it to me now!</option>
<option>Meh...</option>
</select>
</label>
</div>
<div id="followup2">
<label>Why not?<br />
<textarea></textarea>
</label>
</div>
</div>
JavaScript
// Whenever the user changes the value of
// the element with ID "choices", perform
// this function.
$('#choices').on('change', function() {
// Grab the choice value
var choice = $(this).val();
// Cache the "choices-followup" object.
// Every time to you call $('anything'), jQuery
// goes through the entire DOM looking for that
// object. Prevent this by making the lookup
// once, and caching the value.
var choices_followup = $('#choices-followup');
// No matter what the choice, hide all possible
// follup fields.
$('div', choices_followup).hide();
// Also, reset their values.
$('select, textarea, input', choices_followup).val('');
// If this, then that, etc.
switch(choice) {
case '1':
$('#followup1').show();
break;
case '2':
$('#followup2').show();
break;
}
});
.CSS
#choices-followup > div { display: none; }