使用jQuery操作input的value值

使用jQuery操作input的value值

表单控件是我们的重中之重,因为一旦牵扯到数据交互,离不开form表单的使用,比如用户的注册登录功能等

那么通过上节知识点我们了解到,我们在使用jquery方法操作表单控件的方法:

$(selector).val()//设置值和获取值

看如下HTML结构:

使用jQuery操作input的value值
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="">
            <input type="radio" name="sex"  value="112" />男
            <!-- 设置cheked属性表示选中当前选项 -->
            <input type="radio" name="sex"  value="11" checked="" />女
            <input type="radio" name="sex"  value="11" />gay

            <input type="checkbox" value="a" checked=""/>吃饭
            <input type="checkbox" value="b" />睡觉
            <input type="checkbox" value="c" checked=""/>打豆豆
    
    <!-- 下拉列表 option标签内设置selected属性 表示选中当前 -->
            <select name="timespan"    >  
                <option value="1">8:00-8:30</option>  
                <option value="2" selected="">8:30-9:00</option>  
                <option value="3">9:00-9:30</option>  
            </select>  
            <input type="text" name=""  />
    </form>
    
</body>
</html>
使用jQuery操作input的value值

页面展示效果:

使用jQuery操作input的value值

操作表单控件代码如下:

使用jQuery操作input的value值
<script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        
        $(function(){
            // 一、获取值
                //1.获取单选框被选中的value值
                console.log($('input[type=radio]:checked').val())

                //2.复选框被选中的value,获取的是第一个被选中的值
                console.log($('input[type=checkbox]:checked').val())
          
          console.log($('#timespan option:selected').val());  //获取到的是第二个值 因为你规定了取值的selected
          console.log($('#timespan option').val()); //获取到第一个值 因为是从第一个开始获取的
//3.下拉列表被选中的值 var obj = $("#timespan option:selected"); // 获取被选中的值 var time = obj.val(); console.log(time); // 获取文本 var time_text = obj.text(); console.log("val:"+time+" text"+ time_text ); //4.获取文本框的value值 console.log($("input[type=text]").val())//获取文本框中的值 // 二.设置值 //1.设置单选按钮和多选按钮被选中项
          $('input[type=radio]').val(['112']); //对所有type都是radio的value的值是112的为你选中的input
          // $('input[type=radio]').val(['112']);
        $('input[type=checkbox]').val(['a','b']); //这个是选中value是 a 和b 的input
//2.设置下拉列表框的选中值,必须使用select /*因为option只能设置单个值,当给select标签设置multiple。 那么我们设置多个值,就没有办法了,但是使用select设置单个值和多个值都可以 */ $('select').val(['3','2']) //3.设置文本框的value值 $('input[type=text]').val('试试就试试') }) </script>

.