单选按钮、复选框、下拉框的回显


在前端页面中,经常需要根据需要来进行信息的回显,如果是普通的文本,那么用input框进行回显好就好了,有时会有单选按钮radio、复选框checkbox、下拉框select和option,需要根据特定的情况来自动选中单选按钮,自动勾选复选框,自动设置好下拉框的option等。其实主要是在html的js代码,弄过好几次了,老是忘记,所以在这里记录一下。

1、单选按钮radio的回显

先看表:
在这里插入图片描述
根据sex字段的值来设置单选按钮radio的选中,0选中女,1选中男。

代码如下:

public class User {

    private Integer id;

    private String name;

    private Integer sex;

    private Date birth;

    private String address;

    private Integer pro;

    private String email;

    private String favo;

    public String getFavo() {
        return favo;
    }

    public void setFavo(String favo) {
        this.favo = favo;
    }

    public Integer getPro() {
        return pro;
    }

    public void setPro(Integer pro) {
        this.pro = pro;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

dao层相关:

/**
 * @Description
 * @ClassName UserDao
 * @Author yanchengzhi
 * @date 2021.06.20 17:13
 */
public class UserDao {

    /*
    * @description: 获取所有用户信息
    * @param: []
    * @return: List<User>
    * @author: yanchengzhi
    * @date: 2021/6/20 17:13
    */
    public User getFirstUser(){
        String sql = "select id,name,sex,birth,address,pro,email,favo from user limit 0,1";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                User u = new User();
                u.setId(resultSet.getInt("id"));
                u.setName(resultSet.getString("name"));
                u.setSex(resultSet.getInt("sex"));
                u.setBirth(resultSet.getDate("birth"));
                u.setAddress(resultSet.getString("address"));
                u.setPro(resultSet.getInt("pro"));
                u.setEmail(resultSet.getString("email"));
                u.setFavo(resultSet.getString("favo"));
                return u;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
            DataSourceManager.closeResultSet(resultSet);
        }
        return null;
    }

}

servlet相关:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
页面相关:

<%--
  Created by IntelliJ IDEA.
  User: 17605
  Date: 2021/6/20
  Time: 16:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>用户信息展示页面</title>
    <script type="text/javascript" src="/servlet_demo/static/js/jquery-2.1.4.min.js"></script>
</head>
<body>
<table border="1" style="width: 100%; border-collapse: collapse;">
    <thead>
    <tr style="height: 50px;">
        <th>姓名</th>
        <th>性别</th>
        <th>生日</th>
        <th>兴趣爱好</th>
        <th>地址</th>
        <th>省份</th>
        <th>邮箱</th>
    </tr>
    </thead>
    <tbody>
    <c:if test="${not empty requestScope.user}">
        <input type="text" id="me" value="${user.sex}" style="display: none;"/>
        <tr style="text-align: center;height: 50px;">
            <td>${user.name}</td>
            <td>
                <input type="radio" name="sex" value = "0" /> 女
                <input type="radio" name="sex" value = "1" /> 男
            </td>
            <td>${user.birth}</td>
            <td>
                <input type="checkbox" name="favo" value="1" /> 唱歌
                <input type="checkbox" name="favo" value="2" /> 阅读
                <input type="checkbox" name="favo" value="3" /> 徒步
                <input type="checkbox" name="favo" value="4" /> 旅行
            </td>
            <td>${user.address}</td>
            <td>
                <select name="pro" id="pro" style="width: 100px;">

                </select>
            </td>
            <td>${user.email}</td>
        </tr>
    </c:if>
    <c:if test="${empty requestScope.user}">
        <tr style="text-align: center;height: 50px;">
            <td style="text-align: center;" colspan="5">暂无任何信息!</td>
        </tr>
    </c:if>
    </tbody>
    <tfoot></tfoot>
</table>
<script>

// 根据value值回显单选radio
var sexValue = $('#me').val();
$(':radio[name="sex"][value="'+ sexValue +'"]').prop("checked","checked");

</script>
</body>
</html>

效果:
在这里插入图片描述
根据value值成功的勾选了男,最主要的就js里的一句代码:
在这里插入图片描述

2、复选框checkbox的回显

原理都一样,都是根据value值来设置选中的。

只用改页面代码:
在这里插入图片描述
在这里插入图片描述
以上均为添加内容,效果:
在这里插入图片描述
复选框根据后端返回的value值自动勾选了,没问题。

3、下拉框select的option回显

相关代码:
在这里插入图片描述

public class ProvinceDao {

    /*
    * @description: 获取所有省份
    * @param: []
    * @return: java.util.List<com.ycz.domain.Province>
    * @author: yanchengzhi
    * @date: 2021/6/20 19:04
    */
    public List<Province> getAllProvinces(){
        List<Province> provinces = new ArrayList<>();
        String sql = "select id,name,description from province";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                Province p = new Province();
                p.setId(resultSet.getInt("id"));
                p.setName(resultSet.getString("name"));
                p.setDescription(resultSet.getString("description"));
                provinces.add(p);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
            DataSourceManager.closeResultSet(resultSet);
        }
        return provinces;
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
前端页面的添加内容:
在这里插入图片描述
在这里插入图片描述
效果:
在这里插入图片描述
option是根据值value来自动选中的,并不是我选中的。

完整的jsp页面代码如下:

<%--
  Created by IntelliJ IDEA.
  User: 17605
  Date: 2021/6/20
  Time: 16:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>用户信息展示页面</title>
    <script type="text/javascript" src="/servlet_demo/static/js/jquery-2.1.4.min.js"></script>
</head>
<body>
<table border="1" style="width: 100%; border-collapse: collapse;">
    <thead>
    <tr style="height: 50px;">
        <th>姓名</th>
        <th>性别</th>
        <th>生日</th>
        <th>兴趣爱好</th>
        <th>地址</th>
        <th>省份</th>
        <th>邮箱</th>
    </tr>
    </thead>
    <tbody>
    <c:if test="${not empty requestScope.user}">
        <input type="text" id="me" value="${user.sex}" style="display: none;"/>
        <input type="text" id="me2" value="${user.pro}" style="display: none;"/>
        <input type="text" id="me3" value="${user.favo}" style="display: none;"/>
        <tr style="text-align: center;height: 50px;">
            <td>${user.name}</td>
            <td>
                <input type="radio" name="sex" value = "0" /> 女
                <input type="radio" name="sex" value = "1" /> 男
            </td>
            <td>${user.birth}</td>
            <td>
                <input type="checkbox" name="favo" value="1" /> 唱歌
                <input type="checkbox" name="favo" value="2" /> 阅读
                <input type="checkbox" name="favo" value="3" /> 徒步
                <input type="checkbox" name="favo" value="4" /> 旅行
            </td>
            <td>${user.address}</td>
            <td>
                <select name="pro" id="pro" style="width: 100px;">

                </select>
            </td>
            <td>${user.email}</td>
        </tr>
    </c:if>
    <c:if test="${empty requestScope.user}">
        <tr style="text-align: center;height: 50px;">
            <td style="text-align: center;" colspan="5">暂无任何信息!</td>
        </tr>
    </c:if>
    </tbody>
    <tfoot></tfoot>
</table>
<script>
    // 动态添加option
    $.ajax({
        url: '/servlet_demo/myServlet.do?COMMAND=GET_ALL_PRO',
        type: 'get',
        dataType: 'json',
        success: function(result) {
            var content = "";
            for(var i=0;i<result.length;i++) {
                content += '<option value="' + result[i].id + '">' + result[i].name + '</option>';
            }
            $('#pro').html(content);
            // 根据value值回显option
            var proValue = $('#me2').val();
            $('#pro option[value="' + proValue + '"]').attr("selected","selected");
        }
    });

    // 根据value值勾选复选框
    var favos = $('#me3').val().split(","); // 分割获取字符串数组
    // 获取所有复选框的value值
    var ids = new Array();
    // 所有复选框
    var boxes = $('input[name="favo"]');
    for(var i=0;i<boxes.length;i++){
        ids.push(boxes[i].defaultValue);
    }
    for(var i=0;i<ids.length;i++){
        for(var j=0;j<favos.length;j++){
          if(ids[i] == favos[j]) {
               $('input[name = "favo"][value="' + favos[j] + '"]').attr('checked',true);
            }
        }
     }

    // 根据value值回显单选radio
    var sexValue = $('#me').val();
    $(':radio[name="sex"][value="'+ sexValue +'"]').prop("checked","checked");

</script>
</body>
</html>

最终效果:
在这里插入图片描述
在这里插入图片描述
单选按钮、复选框、下拉框回显都是成功的。

最主要的是js的3行代码:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值