DIV CSS 佈局教程網

select multiple 全選與取消全選的實作(jQuery 與原生 JS)
編輯:關於JavaScript     

多選下拉(<select multiple>)要怎麼一次選全部?其實關鍵只有一句:把每個 option 的 selected 屬性設為真。取消全選則設回假。剩下就是怎麼迭代這些 option 的問題。

用 jQuery 迭代並取值

先感受一下怎麼走訪 children:

$("select").change(function(){
  var n = $(this).children().length;
  var i = 1;
  $(this).children().each(function(){
    if(i == n)
    {
      alert($(this).text());
    }
    i++;
  });
});

全選函式

把 children() 與 attr 組合起來,全選就完成了:

function selectall()
{
  $("select").children().each(function(){
    $(this).attr("selected", "selected");
  });
}

取消全選只要把屬性移除:

function selectNone()
{
  $("select").children().each(function(){
    $(this).removeAttr("selected");
  });
}

要注意的是,在 jQuery 1.6 之後 attr 與 prop 的分工被明確化:selected、checked 這類「當前狀態」該用 prop("selected", true),attr 則代表 HTML 初始狀態。混用會出現「設了卻沒生效」的怪現象。

原生 JavaScript 版本

不依賴任何函式庫時,直接對 options 集合跑迴圈即可:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script type="text/javascript">
<!--
function selectAll()
{
  var opts = document.getElementById("CourseList");
  for(var i = 0; i < opts.length; i++)
  {
    opts[i].selected = true;
  }
}

function selectCancel()
{
  var opts = document.getElementById("CourseList");
  for(var i = 0; i < opts.length; i++)
  {
    opts[i].selected = false;
  }
}
//-->
</script>
</head>
<body>
<select id="CourseList" name="CourseList" multiple="multiple" size="20" style="width:230px;">
  <option value="003">(003) 消費者行為與銷售心理</option>
  <option value="004">(004) 產品策劃與市場推廣</option>
  <option value="005">(005) 品牌定位與廣告原理</option>
</select>
<input type="button" onclick="selectAll()" value="全選">
<input type="button" onclick="selectCancel()" value="取消全選">
</body>
</html>

原範例的 </form> 是個多餘的閉合標籤,這裡已經移除。另外補一個實務上很實用的延伸:如果要做「全選/取消」切換,只要判斷目前是否全數已選,再決定要設 true 還是 false;若要取得已選項目,用 opts.options[i].selected 挑出來組陣列,比 select.value 只能拿到單一值好用得多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved