获取type=radio属性的value值,获取选中的option的值,给特定value的option设定选中

本文详细介绍使用jQuery操作单选按钮(Radio)和下拉选择框(Select)的多种方法,包括获取和设置选中状态、初始化选中值以及根据索引或值选择选项。特别强调了在操作Radio和Select元素时,应使用prop方法而非attr以确保正确结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

 

1.获取选中值,三种方法都可以:

$('input:radio:checked').val();
$("input[type='radio']:checked").val();
$("input[name='rd']:checked").val();

2.设置第一个Radio为选中值:
$('input:radio:first').attr('checked', 'checked');
或者
$('input:radio:first').attr('checked', 'true');
注:attr("checked",'checked')= attr("checked", 'true')= attr("checked", true)
3.设置最后一个Radio为选中值:
$('input:radio:last').attr('checked', 'checked');
或者
$('input:radio:last').attr('checked', 'true');
4.根据索引值设置任意一个radio为选中值:
$('input:radio').eq(索引值).attr('checked', 'true');索引值=0,1,2....



4.value = 该值为radio的动态需要设置选中的值//
$("input[type=radio][name=radioType][value='"+value+"']").attr("checked",true);
第一次确实是可以选中,但是当两个选中相互切换的时候就会出现即使你设置了attr("checked",false)会失效的情况


正确方式:
if(value == '1'){
    $('.testSelectOne').prop("checked", "checked");
    $('.testSelectTwo').prop("checked", "");
}else if(value == '0'){
    $('.testSelectOne').prop("checked", "");
    $('.testSelectTwo').prop("checked", "checked");
}

必须使用prop,不能使用attr属性否则不能成功。对于这种像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。

注意:
在编辑按钮radio时,要注意name属性的值一定要相同;
初始化让单选框选中有4种方法可以实现:
1、checked
2、checked='checked'(建议用此方法,此方法对浏览器可以有很好的兼容性)
3、checked='true'
4、checked=true




option的值
<select id="testSelect "  name="" class="valid">   
  <option   value="1">text1</option>   
  <option   value="2">text2</option>   
 </select>
 
 

1.给特定value值得option设定选中
var type=1;
 $(".valid option[value='"+type+"']").attr("selected",true);
2.获取选中的值
    javascript原生的方法
 
         1:拿到select对象: var  myselect=document.getElementById("testSelect ");
 
          2:拿到选中项的索引:var index=myselect.selectedIndex ;             // 
            selectedIndex代表的是你所选中项的index
  
         3:拿到选中项options的value:  myselect.options[index].value;
  
         4:拿到选中项options的text:  myselect.options[index].text;
    jq方法
         $('#testSelect option:selected').text();//选中的文本

        $('#testSelect option:selected') .val();//选中的值

        $("#testSelect ").get(0).selectedIndex;//索引


          $("#tesetSelect").find("option:selected").text();//选中的文本
              …….val();
              …….get(0).selectedIndex;



祝工作顺利,身体健康
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值