根据下拉选择JavaScript显示/隐藏多个DIV



我正在尝试创建一个表单,该表单将根据下拉菜单中选择的内容显示更多字段。如果选择了1位来宾,则会出现1个表格。如果2,则出现2个表格,依此类推。

我设法获得了第一个Div(GuestFormone(来显示/隐藏,具体取决于是否选择了1位来宾,但我正在努力寻找一种解决方案,以使最多6位客人实现这一目标。

这是我到目前为止所拥有的:

html

    <h4>Number of Guests</h4>
<select onchange="numofGuests()">
  <option>Select number of guests</option>
  <option id="guestCountOne">1</option>
  <option id="guestCountTwo">2</option>
  <option id="guestCountThree">3</option>
  <option id="guestCountFour">4</option>
  <option id="guestCountFive">5</option>
  <option id="guestCountSix">6</option>
</select>
<div id="guestFormOne">
  <h4>Guest 1</h4>
  <input type="text" placeholder="Name">
  <select id="guest1_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest1_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div id="guestFormTwo">
  <h4>Guest 2</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>

javascript

   function numofGuests() {
      if (document.getElementById("guestCountOne").selected) {
        document.getElementById("guestFormOne").style.display = "block";
      } else {
        document.getElementById("guestFormOne").style.display = "none";
      }
    }

帮助您将不胜感激,因为我觉得我试图让它工作。

您可以动态地添加任意数量的数量:

function numofGuests(val) {
    document.getElementById('guestFormOne').innerHTML = "";
    for (i = 0; i < parseInt(val.value); i++) { 
        document.getElementById('guestFormOne').innerHTML += '<h4>Guest '+(i+1)+'</h4><input type="text" placeholder="Name"><select  id="guest'+(i+1)+'_meal"><option>Meal Choice</option> <option>Buffet</option><option>Gluten Free</option><option>Dairy Free</option><option>Vegan</option></select><select id="guest'+(i+1)+'_age"><option>Age</option><option>Adult</option><option>Child under 5</option><option>Child 6 - 12</option></select><input type="text" placeholder="Allergies?">';
    }      
}    
<h4>Number of Guests</h4>
<select onchange="numofGuests(this)">
  <option>Select number of guests</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
</select>
<div id="guestFormOne"></div>

您会将所有隐藏的访客表单放入一个集合中,然后循环通过该集合,直到您达到下拉菜单中选择的计数为止。来宾表格不需要id S,您只会给他们所有相同的CSS课程。您还将默认设置所有访客表格(也使用CSS A类,而不是使用内联样式(。

最后,不要使用内联HTML事件属性(onchangeonclick等(。这是一种古老的技术,引起许多问题,需要死亡。相反,在JavaScript中进行所有活动。

var guestCount = document.getElementById("guestCount");
guestCount.addEventListener("change", numOfGuests);
// Get all the guest forms into an collection
var guestForms = document.querySelectorAll(".guestForm");
function numOfGuests() {
  // Loop through the guest forms based on the number selected
  guestForms.forEach(function(v,i){
    if(i < guestCount.value) {
      v.classList.remove("hidden");
    }
  });
}
.hidden { display:none; }
<h4>Number of Guests</h4>
<select id="guestCount">
  <option>Select number of guests</option>
  <option id="guestCountOne">1</option>
  <option id="guestCountTwo">2</option>
  <option id="guestCountThree">3</option>
  <option id="guestCountFour">4</option>
  <option id="guestCountFive">5</option>
  <option id="guestCountSix">6</option>
</select>
<div class="guestForm hidden">
  <h4>Guest 1</h4>
  <input type="text" placeholder="Name">
  <select id="guest1_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest1_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 2</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 3</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 4</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 5</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 6</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 2</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>
<div class="guestForm hidden">
  <h4>Guest 2</h4>
  <input type="text" placeholder="Name">
  <select id="guest2_meal">
   <option>Meal Choice</option>
   <option>Buffet</option>
   <option>Gluten Free</option>
   <option>Dairy Free</option>
   <option>Vegan</option>
  </select>
  <select id="guest2_age">
   <option>Age</option>
   <option>Adult</option>
   <option>Child under 5</option>
   <option>Child 6 - 12</option>
  </select>
  <input type="text" placeholder="Allergies?">
</div>

现在,显示了所有这些,最好的解决方案是动态地创建客人表格,而不是一遍又一遍地编写相同的html:

var out = document.getElementById("output");
var guestCount = document.getElementById("guestCount");
guestCount.addEventListener("change", makeGuests);
function makeGuests(){
  out.innerHTML = ""; // Clear previous output
  
  // Set up arrays that hold data that the two guest form lists need:
  var meals = ["Meal Choice", "Buffet", "Gluten Free", "Dairy Free", "Vegan"];
  var ages = ["Age", "Adult", "Child under 5", "Child 6 - 12"];
  // Create a loop that iterates the numnber of times specified in the list
  for(var i = 0; i < guestCount.value; i++){
  
    // Create and configure a guest form, element by element...
    var container = document.createElement("div");
    
    var heading = document.createElement("h4");
    heading.textContent = "Guest " + (i + 1);
    container.appendChild(heading); // Put new element in container
    
    var txtName = document.createElement("input");
    txtName.type = "text"
    txtName.placeholder = "Name";
    txtName.name = "name";
    container.appendChild(txtName);
    
    var mealList = document.createElement("select");
    mealList.id = "guest" + (i + 1) + "_meal" ;
    // Loop through the meals array
    meals.forEach(function(value){
      // And, create an option for each one
      var opt = document.createElement("option");
      opt.textContent = value;
      mealList.appendChild(opt);
    });
    container.appendChild(mealList);
  
    var ageList = document.createElement("select");
    ageList.id = "guest" + (i + 1) + "_age" ;
    ages.forEach(function(value){
      var opt = document.createElement("option");
      opt.textContent = value;
      ageList.appendChild(opt);
    }); 
    container.appendChild(ageList);
  
    // Make final input
    var allergies = document.createElement("input");
    allergies.type = "text"
    allergies.placeholder = "Allergies?";
    container.appendChild(allergies);
  
    // Everything is made and in the container. Add the container to the document
    out.appendChild(container);
  }
}
.hidden { display:none; }
<h4>Number of Guests</h4>
<select id="guestCount">
  <option>Select number of guests</option>
  <option id="guestCountOne">1</option>
  <option id="guestCountTwo">2</option>
  <option id="guestCountThree">3</option>
  <option id="guestCountFour">4</option>
  <option id="guestCountFive">5</option>
  <option id="guestCountSix">6</option>
</select>
<div id="output"></div>

认为有些不同。并使用以下策略。

首先隐藏所有div

  1. div的ID如guestForm1guestForm2等。
  2. 将下拉的ID传递给JavaScript并获取其选定的值
  3. selectedValue作为整数循环到1(或相对(,并使用id=‘guestForm’+loopIndex找到div
  4. 使该Div display block

我可以尝试将一些代码作为示例

示例

<select onchange='showForms(this)'>
<option value='0'>None</option>
 <option value='1'>1</option>
 <option value='2'>2</option>
 <option value='3'>3</option>
 <option value='4'>4</option>
 <option value='5'>5</option>
 <option value='6'>6</option>
</select>

<div id='guestForm1' style='display:none'>11</div>
<div id='guestForm2' style='display:none'>22</div>
<div id='guestForm3' style='display:none'>33</div>
<div id='guestForm4' style='display:none'>44</div>
<div id='guestForm5' style='display:none'>55</div>
<div id='guestForm6' style='display:none'>66</div>

javascript

function showForms(dd)
{
    var ddVal=dd[dd.selectedIndex].value;
  for(i=1;i<=6;i++)
  {
     document.getElementById('guestForm'+i).style.display='none';
  }

  for(i=1;i<=ddVal;i++)
  {
     document.getElementById('guestForm'+i).style.display='block';
  }
}

注意,如果不存在某些ID的DIV,您仍然应该添加NULL检查

有很少的方法开始构建应用程序。以下演示构建了一个从事2个作业的应用程序,并在需要时旨在扩展其他功能。

  • form#fX上的单击事件听。

  • 单击时,它将事件在2个按钮之间委派并忽略任何其他点击。

  • 它所做的第一个工作是从<template>为每个来宾生成<fieldset>。来宾的数量由input[type="number"]#qty的用户输入确定。此时,揭示了input[type="submit"]按钮。

  • 第二个工作是将表单数据提交给服务器。此时,显示一条消息,通知用户数据已发送并提供了一个链接。

  • 链接滚动到iframe#view显示服务器的响应。

  • 此演示可以进行无限量的客人,每个客人都有唯一的#id,其所有儿童节点都有唯一的[name]属性。

注意:此演示将数据发送到实时测试服务器

参考

事件委托

htmlformcontrolscollection

模板文字

&lt; template&gt;标签

演示

var idx = 0;
var fX = document.forms.fX;
var Xf = fX.elements;
fX.addEventListener('click', delegateClick, false);
function delegateClick(e) {
  if (e.target !== e.currentTarget) {
    if (e.target.value === 'Process') {
      var qty = Xf.qty.valueAsNumber;
      idx = generateGuest(qty, idx);
      e.target.nextElementSibling.style.display = "inline-block";
    } else if (e.target.type === 'submit') {
      e.target.nextElementSibling.style.display = "block";
      Xf.msg.innerHTML = `Data sent. <a href='#view'>View response.</a>`;
    } else {
      return;
    }
  } else {
    return;
  }
}
function generateGuest(qty, idx) {
  var allx = idx + qty;
  for (idx; idx < allx; idx++) {
    var temp = document.getElementById('tmp');
    var cont = temp.content.getElementById('guest');
    var dupe = document.importNode(cont, true);
    var fset = Array.from(dupe.querySelectorAll('*'));
    dupe.id = `guest${idx}`;
    dupe.name = dupe.id;
    fset.map(function(node, index, fset) {
      fset[0].textContent = `Guest ${idx}`;
      fset[1].name = `nam${idx}`;
      fset[2].name = `eat${idx}`;
      fset[8].name = `med${idx}`;
      fset[9].name = `age${idx}`;
    });
    fX.appendChild(dupe);
  }
  return idx;
}
html {
  font: 400 16px/1.5 Consolas
}
fieldset {
  width: 65%
}
select,
input,
button,
output {
  font: inherit;
  display: inline-block
}
select,
input[type="text"] {
  width: 45%
}
select {
  padding: 4px
}
#qty {
  width: 5ch
}
input:not([type="text"]) {
  font-variant: small-caps
}
input[type="submit"],
#msg {
  display: none
}
#view {
  display: block;
  margin: 20px 0 0 0;
}
<form id='fX' action='https://httpbin.org/post' method='post' target='view'>
  <fieldset id='set'>
    <legend>Guest Register</legend>
    <input id='qty' type='number' min='1' max='99' value='1'>
    <input type='button' value='Process'>
    <input type='Submit'>
    <output id='msg'></output>
  </fieldset>
  <hr>
  <template id='tmp'>
  <fieldset id='guest' name='guest'>
    <legend>Guest&nbsp;</legend>
    <input name='nam' type="text" placeholder="Name">
    <select name='eat'>
   <option default>Diet</option>
   <option value='norm'>Buffet</option>
   <option value='tran'>Gluten Free</option>
   <option value='lact'>Dairy Free</option>
   <option value='vege'>Vegan</option>
  </select>
    <input name='med' type="text" placeholder="Allergies">
    <select name='age'>
   <option default>Age</option>
   <option value='18'>Adult</option>
   <option value='05'>Child under 5</option>
   <option value='12'>Child 6 - 12</option>
  </select>
  </fieldset>
  </template>
</form>
<iframe src='about:blank;' id='view' name='view' width='75%' height='75%' frameborder='0'></iframe>

最新更新