關於 CHECKBOX 與 JS、PHP 協調工作的問題

來源:互聯網
上載者:User

    在html中使用checkbox如下:

    <form name="frm1">
    <input type="checkbox" id="mycouse1" name="mycouse[]" value="datastruct">資料結構
    <input type="checkbox" id="mycouse2" name="mycouse[]" value="c++">C++
    <input type="checkbox" id="mycouse3" name="mycouse[]" value="c#">C#
    <input type="checkbox" id="mycouse4" name="mycouse[]" value="php">PHP
    </form>

    注意checkbox名中的“[]”字元,因為是把checkbox作為數組,在php中才能用foreach方法取得選中的值。

    但在js中document.frm1.mycouse[].length方法卻不能用。只有類似於document.frm1.mycouse.length才可以,這樣php就只能取選中的最後一個 mycouse 值了,不能取得所有的選中的 mycouse 值。

    解決辦法:document.frm1["mycouse[]"].length。把整個form看作一個數組,checkbox[] 作為其中一個元素就可以了。

    checkbox_mycouse = document.frm1["mycouse[]"];
    for(var i=0; i<=checkbox_mycouse.length-1; i++)
    {
      if(checkbox_mycouse[i].checked)
        count++;
    }
    alert('有' + count + '選項被選中。');

    其實,如果 name="mycouse[]" 為 name="mycouse",則很簡單:
    for(var i=0; i<=document.frm1.mycouse.length-1; i++)
    {
      if(document.frm1.mycouse[i].checked)
        count++;
    }

    作者:張慶(網眼) ,微博:http://t.qq.com/zhangking
    來自“網眼視界”:http://blog.why100000.com
    “十萬個為什麼”電腦學習網:http://www.why100000.com
     2012-8-22

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.