Jquery操作select

来源:互联网 发布:mac好用的视频播放器 编辑:程序博客网 时间:2024/05/16 15:09

Javascript代码

添加“江苏”到下拉框的最后一位

1$('#add_to_last').click(function(){
2    $('#select').append('
3<OPTION value="江苏"></OPTION>
4  
5江苏
6  
7');
8});

添加“安徽”到下拉框的第一位

Javascript代码

1$('#add_to_first').click(function(){
2    $('#select').prepend('
3<OPTION value="安徽"></OPTION>
4  
5安徽
6  
7');
8});

获取当前的selectIndex(当前选中的下拉菜单的项目的索引)

Javascript代码

1$('#get_select_index').click(function(){
2    alert($('#select option:selected').attr("index"));
3});

移除下拉菜单最后一个项目

Javascript代码

1$('#remove_last_option').click(function(){
2    $('#select option:last').remove();
3});

移除除了第一个之外的所有选项

1$('#remove_all_option_except_first').click(function(){
2    $('#select option').not(':first').remove();
3});

获取下拉菜单最大索引值

1$('#get_max_index').click(function(){
2    var maxIndex=$("#select option:last").attr("index");
3    alert(maxIndex);
4});

=====================================================================

  1. //获取第一个option的值  
  2. $('#test option:first').val();  
  3. //最后一个option的值   
  4. $('#test option:last').val();  
  5. //获取第二个option的值  
  6. $('#test option:eq(1)').val();  
  7. //获取选中的值  
  8. $('#test').val();  
  9. $('#test option:selected').val();  
  10. //设置值为2的option为选中状态  
  11. $('#test').attr('value','2');  
  12. //设置第一个option为选中  
  13. $('#test option:last').attr('selected','selected');  
  14. $("#test").attr('value' , $('#test option:last').val());  
  15. $("#test").attr('value' , $('#test option').eq($('#test option').length - 1).val());  
  16. //获取select的长度  
  17. $('#test option').length;  
  18. //添加一个option  
  19. $("#test").append("<option value='9'>ff</option>");  
  20. $("<option value='9'>ff</option>").appendTo("#test");  
  21. //添除选中项  
  22. $('#test option:selected').remove();  
  23. //指定项选中  
  24. $('#test option:first').remove();  
  25. //指定值被删除  
  26. $('#test option').each(function(){  
  27.     if( $(this).val() == '5'){  
  28.          $(this).remove();  
  29.      }  
  30. });  
  31. $('#test option[value=5]').remove();  
  32.   
  33. //获取第一个Group的标签  
  34. $('#test optgroup:eq(0)').attr('label');  
  35. //获取第二group下面第一个option的值   
  36. $('#test optgroup:eq(1) :option:eq(0)').val();