首页 > 语言 > JavaScript > 正文

jquery对单选框,多选框,文本框等常见操作小结

2024-05-06 14:30:55
字体:
来源:转载
供稿:网友

一、文本框、单选按钮、复选框、相关操作
代码如下:
var sex=$("input[name='sex']:checked").val();   //获取一组radio被选中项的值 
var item=$("#sel option:selected").text();      //获取select被选中项的文本 
var option_num=$('#sel').val();                 //获取select项目索引
$("#sel")[0].selectedIndex =1;                  //select下拉框的第二个元素为当前选中值
$("input[name='sex']").get(1).checked=true;     //radio单选组的第二个元素为当前选中值

 或者对单选框默认选定设置:
$("input[name='sex']").each(function(){
            if($(this).val()==s){
                $(this).attr("checked",true);
                                //this.checked=true;
            }
        });

Jquery 根据value值设置下拉列表(select)默认选中项
代码如下:
  <select name=sel onchange="bao(this.options[this.options.selectedIndex].value)">
  <option value="">请选择
  <option value="1">Item 1
  <option value="2">Item 2
  <option value="3">Item 3
  </select>
  <script>
  function bao(s)
  {
     txt.value=s;
     //选择后,让第一项被选中,这样,就有Change啦.
     document.all.sel.options[0].selected=true;
 }
 </script>
 <textarea id=txt></textarea>

二、 jQuery获取 Select选择的Text和Value
代码如下:
语法解释:
 $("#select_id").change(function(){//code...});   //为Select添加事件,当选择其中一项 时触发
 var checkText=$("#select_id").find("option:selected").text();  //获取Select选择的Text
 var checkValue=$("#select_id").val();  //获取Select选择的Value
 var checkIndex=$("#select_id ").get(0).selectedIndex;  //获取Select选择的索引值
 var maxIndex=$("#select_id option:last").attr("index");  //获取Select最大的索引值

jQuery设置Select选择的Text和Value:
语法解释:
 $("#select_id ").get(0).selectedIndex=1;  //设置Select索引值为1的项选中
 $("#select_id ").val(4);   //设置Select的Value值为4的项选中
 $("#select_id option[text='jQuery']").attr("selected", true);   //设置 Select的Text值为jQuery的项选中

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选