JS操作表单select详解-选取当前值、重置option等

##JS操作表单select详解-选取当前值、重置option等
对于表单(form)中常用的select选项,经常牵涉到选取的option的index值、value值及文本,本文结合着实例对其进行讲解。

一个select如下

<button type="button" id="pre" onclick()="pre()">pre
</button>
<select id="choose" name ="choose" onchange ="getOptionName()">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
<button type="button" id="next" onclick()="next()">next
</button>

代码的效果图

在这里插入图片描述

###select中常用的操作如下:
1.获取select对象;

var sel=document.querySelector(“#choose”);

2.获取select选中option的index值;

var index=sel.selectedIndex;

3.获取select选中的option的value;

var val=sel.options[index].value;

4.获取select选中的option的text;

var text=sel.options[index].text;

###JS代码实现

<script>
  let sel = document.querySelector('#choose');
  let selarr = [...sel];
  let selarrLength = selarr.length;//select 的长度;
  
  function getOptionName(){
   let first = sel.selectedIndex; //获取改变后的option 值
  }
  function pre(){  //向前的选择
    let current = sel.selectedIndex; //目前option的index
    if(current > 0 ){
      current--;
      sel[current].selected="ture";  //将改变后的option置为selected;
    }
    else{
      alert("已经达到第一个!")
      return false;
    }
  }
  function next(){  //向后选择
    let current= sel.selectedIndex;
    current++;
    console.log(current);
    if(current < selarrLength){
      sel[current].selected="ture";
    }
    else{
        alert("已经达到最后!");
        return false;
    }
  }
</script>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值