Home > Web Front-end > JS Tutorial > Example of dynamically adding options to layui select

Example of dynamically adding options to layui select

亚连
Release: 2018-05-31 17:22:12
Original
3357 people have browsed it

Below I will share with you an example of dynamically adding options to layui select. It has a good reference value and I hope it will be helpful to everyone.

html

<form class="layui-form" action="">
 <p class="layui-form-item proSelect">
   <label class="layui-form-label">产品类别</label>
   <p class="layui-input-block editWidth">
    <select name="productList" lay-verify="required" id="zcySelect">
     <option value=""></option>
     <option value="0">轻松融</option>
     <option value="1">容易融</option>
     <option value="2">快乐融</option>
    </select>
   </p>
  </p>
  <a class="layui-btn layui-btn-small" id="" onclick="addProductClassify()">增加产品类别</a>
</form>
<!--弹窗内容-->
<p id="select_prod" class="layui-form" hidden="hidden">
 <p class="layui-input-inline">
  <input type="text" name="text" required lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
 </p>
</p>
Copy after login

js

//重新渲染表单
function renderForm(){
 layui.use(&#39;form&#39;, function(){
 var form = layui.form();//高版本建议把括号去掉,有的低版本,需要加()
 form.render();
 });
 }
//增加产品类别按钮点击事件
function addProductClassify(){
 layer.open({
  type:1,
  btn:[&#39;确定&#39;,&#39;取消&#39;],
  content:$("#select_prod"),
  area:[&#39;270px&#39;,&#39;160px&#39;],
  //当前层索引参数(index)、当前层的DOM对象(layero)
  yes:function(index,layero){
   //获取input输入的值
   var ivalue=$(layero).find("input").val();
   //获取要添加的option的索引
   var sIndex=$("#zcySelect")[0].options.length-1;
   if(ivalue==null||ivalue==&#39;&#39;){
    layer.msg("请输入产品类别")
   }
   else{
    layer.msg("输入的产品类别是:"+ivalue);
    //为select添加option
    $("#zcySelect").append("<option value="+sIndex+">"+ivalue+"</option>"); 
    renderForm();//表单重新渲染,要不然添加完显示不出来新的option
    layer.close(index);
   }
   $(layero).find("input").val(&#39;&#39;);
  }
 })
}
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use the external module in webpack

Use node.js to package webpack

js experience sharing JavaScript anti-debugging skills

The above is the detailed content of Example of dynamically adding options to layui select. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template