How to set the default value of a dropdown list in layui?
There are two methods to set the default value for a dropdown box using Layui.
Option: Method 1: Setting the value attribute in HTML.
<select name="city" lay-verify="required">
<option value="">请选择城市</option>
<option value="1" {{ data.city === '1' ? 'selected' : '' }}>北京</option>
<option value="2" {{ data.city === '2' ? 'selected' : '' }}>上海</option>
<option value="3" {{ data.city === '3' ? 'selected' : '' }}>广州</option>
</select>
In the example above, we utilized Layui’s template engine to verify if the current data value is equal to the option value. If they are equal, the selected attribute is added to indicate that the option is selected.
Option 2: Assign values using the form module of Layui.
// 初始化下拉框
form.render('select');
// 设置默认值
form.val('selectFilter', {
'city': '1' // 默认选中北京
});
In the example above, we are using the form.val() method to set the default value of the dropdown box. ‘selectFilter’ is the value of the lay-filter attribute of the dropdown element, ‘city’ is the value of the name attribute of the dropdown element, and ‘1’ is the default value to be set.
Note: When using method two, make sure to first load the form module of Layui and call the form.render(‘select’) method to initialize the dropdown list.