为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕无忌1623718 2022-08-18 09:41:28
我正在使用具有多个属性的选择类型,并希望显示与所选选项一样多的输入字段,如果所选选项未选中,但代码的输出仅显示一个输入字段,则删除输入字段。这是代码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>
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

使用 jquery 获取多选的值。这将返回一个数组。相反,在内联样式上,使用类来隐藏所有元素。使用另一个类来定位输入。选择选项时,循环访问元素具有此类并获取其id以检查多选数组是否具有此类。如果数组具有此 ID ,则表示选择了该选项,然后用于删除valhidetechInputtechInputidremoveClasshide


function check(skill) {

  const selectedSkils = $(skill).val();

  $('.techInput').each(function(i, v) {

    if (selectedSkils.indexOf($(v).attr('id')) !== -1) {

      $(v).removeClass('hide');

    } else {

      $(v).addClass('hide')

    }

  })

}

.hide {

  display: none;

}


.techInput {

  margin: 5px;

  padding: 5px;

  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);">

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

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

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

</select>

<div id="css" class='hide techInput'>

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

</div>

<div id="php" class='hide techInput'>

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

</div>

<div id="magento" class='hide techInput'>

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

</div>


查看完整回答
反对 回复 2022-08-18
  • 1 回答
  • 0 关注
  • 119 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号