[Javascript] radio, checkbox, select jquery操作

select

相关概念: option, selected, onChange(没有onSelect事件)

// html demo
<select name="cityCode">
   <option value="021">上海</option>
   <option value="0571" >杭州</option>
   <option value="0576">台州</option>
</select>

相关操作:

// 1. 默认选中value为021的选项
// 方法一:html
<option value="0576" selected>台州</option>
// 方法二: jquery
$('select').val('021');

// 2. 默认选中text为上海的选项(检验无效)
$('select').find('option[text="上海"]').attr('selected', true)

// 3. 获取选中值
$('select').val();

// 4. 获取选中text
$('select').find('option:selected').text();

// 5. 动态删除选项
$('select').find('option[value="0576"]').remove();

// 6.动态添加选项
$('select').append('<option value="010">北京</option>');

// 7. select事件onchange
$(document).ready(function(){
  $('select').on('change', function() {
        alert($(this).val());
    })
});

checkbox

相关概念: checked, onChange, onClick(没有onCheck事件)

<p>水果:</p>
<input type="checkbox" name="fru_1" value="orange">橘子</input>
<input type="checkbox" name="fru_1" value="apple">苹果</input>

<p>蔬菜:</p>
<input type="checkbox" name="veg_1" value="tomato">番茄</input>
<input type="checkbox" name="veg_1" value="potato">土豆</input>
// 1. 设置默认选中,根据value
// 方法一:html
<input type="checkbox" name="fru_1" value="orange" checked>橘子</input>
// 方法二:
$('input[name="fru_1"][value="orange"]').attr('checked', true);
// 方法三:索引
$('input[name="fru_1"]:first').attr('checked', true);
$('input[name="fru_1"]:last').attr('checked', true);
$('input[name="fru_1"]').eq(1).attr('checked', true);

// 2. 设置默认选中,根据text(检验无效)
 $('input[name="fru_1"][text="苹果"]').attr('checked', true);

// 3. 获取选中值
 var checkedElements = $('input[name="fru_1"]:checked');
 alert("选中个数:" + checkedElements.length);
 var valueArr = [];
 $(checkedElements).each(function() {
      valueArr.push($(this).val());
  })
 alert(valueArr);

// 4. checkbox事件change, click事件(对单个框)
$(document).ready(function(){
  $('input[name="fru_1"]').on('change', function() {
         // 判断是否选中
         var checked = this.checked,
        // 或者
        // checked = $(this).is(':checked'),
        // 获取值
          value = $(this).val();
   });

   $('input[name="fru_1"]').on('click', function() {
      // 获取值
     alert($(this).val());
   });
});


radio

相关概念: radio, checked, onChange, onClick

// html demo
<p>水果:</p>
<input type="radio" name="fru_1" value="orange" >橘子</input>
<input type="radio" name="fru_1" value="apple">苹果</input>

<p>蔬菜:</p>
<input type="radio" name="veg_1" value="tomato">番茄</input>
<input type="radio" name="veg_1" value="potato">土豆</input>

相关操作:参考checkbox

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值