动态设置 layui select 为选中状态
// 当前的select的id
$(‘#type’).val(‘你的value值’);
//更新全部
layui.form.render();
layui动态修改select的选中项
通过$(‘select’).val(‘xx’);设置了select的选中项,下拉列表确实被修改的值高亮了,但是select显示的当前选中项依然是默认选项。
坑了一下午,终于发现原来一定要layui.form.render(‘select’);才能更新select的选中项,太坑了。
误区:
一直以为jquery获取select中option被选中的文本值,是这样写的:
$(“#id”).text(); //获取所有option的文本值
实际上应该这样:
$(“#id option:selected”).text(); //获取选中的option的文本值
获取select中option的被选中的value值,
$(“#id”).val(); //获取选中的值
$(“#id option:selected”).val();
js获取select选中的值:
var sel=document.getElementById(“id”);
var index = sel.selectedIndex; // 选中索引
albumid= sel.options[index].value;//要的值
在写报表管理模块时,需要通过条件去筛选符合条件的数据,筛选条件用的布局有select,input等。在调试的过程中一直获取不到select选中的option。于是就查询些资料,发现用select的selected属性可以获取到option的值。下面通过demo来演示:
通过2种方式:
一、jquery方法(页面中必须加载过jquery库)—————————-推荐使用
1:var options=$(“#test option:selected”); //获取选中的项
2:alert(options.val()); //拿到选中项的值
3:alert(options.text()); //拿到选中项的文本
demo代码:
二、通过原生js方法
1:拿到select对象: var myselect=document.getElementById(“test”);
2:拿到选中项的索引:var index=myselect.selectedIndex ; // selectedIndex代表的是你所选中项的index
3:拿到选中项options的value: myselect.options[index].value;
4:拿到选中项options的text: myselect.options[index].text;
推荐使用第一种jqueiry方法去获取select选中的option~~~~