Blogger Information
Blog 25
fans 0
comment 0
visits 13756
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JS操作表单select详解-选取当前值、重置option等
安超
Original
590 people have browsed it

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

对于表单(form)中常用的select选项,经常牵涉到选取的option的index值、value值及文本中,本文结合着实例对其进行讲解。

一个select如下

  1. <button type="button" id="pre" onclick()="pre()">pre
  2. </button>
  3. <select id="choose" name ="choose" onchange ="getOptionName()">
  4. <option value="option1">option1</option>
  5. <option value="option2">option2</option>
  6. <option value="option3">option3</option>
  7. <option value="option4">option4</option>
  8. <option value="option5">option5</option>
  9. </select>
  10. <button type="button" id="next" onclick()="next()">next
  11. </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代码实现

  1. <script>
  2. let sel = document.querySelector('#choose');
  3. let selarr = [...sel];
  4. let selarrLength = selarr.length;//select 的长度;
  5. function getOptionName(){
  6. let first = sel.selectedIndex; //获取改变后的option 值
  7. }
  8. function pre(){ //向前的选择
  9. let current = sel.selectedIndex; //目前option的index
  10. if(current > 0 ){
  11. current--;
  12. sel[current].selected="ture"; //将改变后的option置为selected;
  13. }
  14. else{
  15. alert("已经达到第一个!")
  16. return false;
  17. }
  18. }
  19. function next(){ //向后选择
  20. let current= sel.selectedIndex;
  21. current++;
  22. console.log(current);
  23. if(current < selarrLength){
  24. sel[current].selected="ture";
  25. }
  26. else{
  27. alert("已经达到最后!");
  28. return false;
  29. }
  30. }
  31. </script>

```

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post