如何在多选类型的用户所选选项上动态添加输入字段

我正在使用具有多个属性的选择类型,并希望显示与所选选项一样多的输入字段,如果所选选项未选中,但代码的输出仅显示一个输入字段,则删除输入字段。这是代码


function check(skill) {

  if (skill.value == "css") {

    document.getElementById("css").style.display = "block";

  } else {

    document.getElementById("css").style.display = "none";

  }

  if (skill.value == "php") {

    document.getElementById("php").style.display = "block";

  } else {

    document.getElementById("php").style.display = "none";

  }

  if (skill.value == "magento") {

    document.getElementById("magento").style.display = "block";

  } else {

    document.getElementById("magento").style.display = "none";

  }

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="skills[]" id="skills" multiple onchange="check(this);">

  <option value="css">css</option>

  <option value="php">php</option>

  <option value="magento">magento</option>

</select>

<div id="css" style="display: none;">

  <label for="sel1"></label><input type="text" name="css" id="selc1">

</div>

<div id="php" style="display: none;">

  <label for="sel2"></label><input type="text" name="php" id="selc2">

</div>

<div id="magento" style="display: none;">

  <label for="sel3"></label><input type="text" name="magento" id="selc3">

</div>


慕无忌1623718
浏览 120回答 1
1回答

aluckdog

使用 jquery 获取多选的值。这将返回一个数组。相反,在内联样式上,使用类来隐藏所有元素。使用另一个类来定位输入。选择选项时,循环访问元素具有此类并获取其id以检查多选数组是否具有此类。如果数组具有此 ID ,则表示选择了该选项,然后用于删除valhidetechInputtechInputidremoveClasshidefunction check(skill) {&nbsp; const selectedSkils = $(skill).val();&nbsp; $('.techInput').each(function(i, v) {&nbsp; &nbsp; if (selectedSkils.indexOf($(v).attr('id')) !== -1) {&nbsp; &nbsp; &nbsp; $(v).removeClass('hide');&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; $(v).addClass('hide')&nbsp; &nbsp; }&nbsp; })}.hide {&nbsp; display: none;}.techInput {&nbsp; margin: 5px;&nbsp; padding: 5px;&nbsp; border-radius: 4px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select name="skills[]" id="skills" multiple onchange="check(this);">&nbsp; <option value="css">css</option>&nbsp; <option value="php">php</option>&nbsp; <option value="magento">magento</option></select><div id="css" class='hide techInput'>&nbsp; <label for="sel1"></label><input type="text" name="css" id="selc1" placeholder='css'></div><div id="php" class='hide techInput'>&nbsp; <label for="sel2"></label><input type="text" name="php" placeholder='php' id="selc2"></div><div id="magento" class='hide techInput'>&nbsp; <label for="sel3"></label><input placeholder='magento' type="text" name="magento" id="selc3"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java