对 Select 的各种操作(JQuery)

在写表单时,经常要用到select元素,这个元素相较于其他文本框标签而言有不同。最近在写一个页面表单时需要对select进行各种操作,现将其用法收集并总结如下:

HTML元素:

<select id="relationship" name="relationship" required="true">
    <option value="1">父母</option>
    <option value="2">夫妻</option>
    <option value="3">子女</option>
    <option value="4">朋友</option>
    <option value="5">其他</option>
</select>

required 一般用在做校验判断当前选项内容是否为必填,加了required后页面会有相应的验证。

对其进行各种操作的jQ代码:

$(document).ready(function() {
    //获取下拉框选中项的index属性值
    var selectIndex = $("#relationship").get(0).selectedIndex;
    alert(selectIndex);

    //绑定下拉框change事件,当下来框改变时调用 SelectChange()方法
    $("#relationship").change(function() {
        //todo
    });

    //获取下拉框选中项的value属性值
    var selectValue = $("#relationship").val();
    alert(selectValue);

    //获取下拉框选中项的text属性值
    var selectText = $("#relationship").find("option:selected").text();
    alert(selectText);

    //设置下拉框index属性为5的选项 选中
    $("#relationship").get(0).selectedIndex = 5;

    //设置下拉框value属性为4的选项 选中
    $("#relationship").val(4);

    //设置下拉框text属性为5的选项 选中
    $("#relationship option[text=5]").attr("selected", "selected");
    $("#yyt option:contains('5')").attr("selected", true);

    ////获取下拉框最大的index属性值
    var selectMaxIndex = $("#relationship option:last").attr("index");
    alert(selectMaxIndex);

    //在下拉框最前添加一个选项
    $("#relationship").prepend("<option value='0'>领导</option>");

    //在下拉框最后添加一个选项
    $("#relationship").append("<option value='6'>同事</option>");

    //移除下拉框最后一个选项
    $("#relationship option:last").remove();

    //移除下拉框 index属性为1的选项
    $("#relationship option[index=1]").remove();

    //移除下拉框 value属性为4的选项
    $("#relationship option[value=4]").remove();

    //移除下拉框 text属性为5的选项
    $("#relationship option[text=5]").remove();

    //清空下拉框
    $("#relationship").empty();
});

 

posted @ 2017-01-13 13:25  keang  阅读(1074)  评论(0编辑  收藏  举报