jquery 操作form元素

web开发中经常会碰到表单操作。表单元素的类型有text、password、select、checkbox、radio、textarea、file、hidden、button、image、reset和submit,不包括html5新类型。下面介绍这些常用的表单元素的赋值和取值操作,file类型有时间会另外写篇文章具体介绍。

text、password、textarea、hidden操作:

$("selector").val()  //get value
$("selector").val(value) //set value

select 操作:

$("selector").val()  //get select value
$("selector option:selected").text() //get select text
$("selector").val(value) //set value

radio 操作:

$("selector :checked").val()  //get radio checked value
$("selector [value="+ value+"]").prop('checked', true); //set radio checked by value
$("selector ").eq(index).prop('checked', true); //set radio checked by index

checkbox 操作:

$("selector :checked").val()  //get single checkbox checked value
 
//get  checked array from checkbox group
var checkboxList=[]; 
$("selector :checked").each(function(index,item){
    checkboxList.push($(this).val());
}) 

$("selector [value="+ value+"]").prop('checked', true); //set checkbox checked by value
$("selector ").eq(index).prop('checked', true); //set checkbox checked by index

//set checkbox checked from checked array 
$("selector ").each(function(index,item){                                   
       $(this).prop("checked",$.inArray($(this).val(),checkboxList)!==-1)
})

//set all checkbox checked and not checked 
$("#checkAll").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

//if the checkbox is checked
$("selector ").is(':checked')

// form serialize
$('form').serialize()

综合示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Sign up</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<style type="text/css">
form {
    width: 600px;
    margin: 50px auto;
}
</style>

<body>
    <form class="form-horizontal" role="form">
        <div class="form-group">
            <label for="firstname" class="col-sm-2 control-label">Username:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="username" id="username" placeholder="Your username" value="">
            </div>
        </div>
        <div class="form-group">
            <label for="pwd" class="col-sm-2 control-label">Password:</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" name="password" id="pwd" value="">
            </div>
        </div>
        <div class="form-group">
            <label for="firstname" class="col-sm-2 control-label">Education:</label>
            <div class="col-sm-10">
                <select class="form-control" name="education">
                    <option value=1>--Please select--</option>
                    <option value=1>Primary school</option>
                    <option value=2>Middle school</option>
                    <option value=3>Senior high school</option>
                    <option value=4>University</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="lastname" class="col-sm-2 control-label">Sex:</label>
            <div class="col-sm-10">
                <label class="checkbox-inline">
                    <input type="radio" name="sex" value=1> Male
                </label>
                <label class="checkbox-inline">
                    <input type="radio" name="sex" value=0> Female
                </label>
            </div>
        </div>
        <div class="form-group">
            <label for="interest" class="col-sm-2 control-label">Interest:</label>
            <div class="col-sm-10">
                <label class="checkbox-inline">
                    <input type="checkbox" name="interest" value=0>Books
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" name="interest" value=1>Music
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" name="interest" value="2">Movies
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" name="interest" value="3">Sports
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" name="interest" value="4">Travel
                </label>
            </div>
        </div>
        <div class="form-group">
            <label for="introduction" class="col-sm-2 control-label">Introduction:</label>
            <div class="col-sm-10">
                <textarea name="introduction" class="form-control" rows="4"></textarea>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-success">Sign up</button>
            </div>
        </div>
    </form>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    $(function() {
        var data = {
            username: "Ross",
            password: "123456",
            education: 2,
            sex: 1,
            interest: [0, 1, 4],
            introduction: "My name is Rosste"
        };

        //set value when form type is "text"、"password"、"hidden"、"textarea"
        $("input[name='username']").val(data.username);
        $("input[name='password']").val(data.password);
        $("textarea").val(data.introduction);

        //set select value
        $("select[name='education']").val(data.education);

        //set radio checked by value
        $("input[name='sex'][value=" + data.sex + "]").prop('checked', true);

        //set radio checked by index
        // $("input[name='sex']").eq(0).prop('checked', true);  

        //set checkbox group checked from checked array
        $("input[name='interest']").each(function(index, item) {
            $(this).prop("checked", $.inArray(parseInt($(this).val()), data.interest) !== -1)
        })

        //set checkbox checked by value
        // $("input[name='interest']").eq(0).prop('checked', true);

        //set checkbox checked by value
        // $("input[name='interest'][value=3]").prop('checked', true);  



        $("button").on("click", function(event) {
            //prevent it from submitting a form
            event.preventDefault();

            //get value when form type is "text"、"password"、"hidden"、"textarea"
            console.log($("input[type='text']").val(), "username")
            console.log($("input[type='password']").val(), "password")
            console.log($("textarea").val(), "introduction")

            //get select value
            console.log($("select").val(), "education")
                //get select text
                // console.log($("select option:selected").text(),"education text")

            //get checked value
            console.log($("input[type='radio']:checked").val(), "Sex");

            //get checked array from checkbox group
            var checkboxList = [];
            $("input[type='checkbox']:checked").each(function(index, item) {
                checkboxList.push(parseInt($(this).val()));
                console.log(checkboxList, "checkboxList");
            })

            //serialize the form for ajax to send to backend
            console.log(decodeURIComponent($('form').serialize()), "serialize")

        })

    })
    </script>
</body>

</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • $(”p”).addClass(css中定义的样式类型); 给某个元素添加样式 $(”img”).attr({sr...
    专注寒冰三千岁阅读 514评论 0 4
  • Attribute: $("p").addClass(css中定义的样式类型); 给某个元素添加样式 $("img...
    扑克脸_457e阅读 599评论 0 1
  • 本人做php的,最近发现JS真的是博大精深啊,比PHP难.在HTML中,表单是由form元素来表示的,但是在jav...
    linfree阅读 2,241评论 3 17
  • Bootstrap是什么? 一套易用、优雅、灵活、可扩展的前端工具集--BootStrap。GitHub上介绍 的...
    凛0_0阅读 10,936评论 3 184
  • 我近两天看了两部老电影《后会无期》和《三傻大闹宝莱坞》,随着我看电影的次数越多,越来越发现自己的感受力很弱。当释梦...
    晓丽姐阅读 134评论 0 3