【前端小代碼】選中checkbox多選框,將值填入select中option中

通過js實現
代碼如下

<script>
function checkbox()
{
    var str=document.getElementsByName("box");
    var shosetype=document.getElementById("select");  
    var objarray=str.length;
    var chestr="";
    var option = '';
    for (i=0;i<objarray;i++)
    {
       if(str[i].checked == true)
       {
            chestr+=str[i].value+",";
            option += '<option value="' + i + '">' + str[i].value + '</option>';
       }
    }
    shosetype.innerHTML=option;
    if(chestr == "")
    {
      alert("請先選擇一個愛好~!");
    }
    else
    {
      alert("您先擇的是:"+chestr);
    }
}
</script>

html代碼

選擇您的愛好:
  <input type="checkbox" name="box" id="box1" value="跳水" />跳水
  <input type="checkbox" name="box" id="box2" value="跑步" />跑步
  <input type="checkbox" name="box" id="box3" value="聽音樂" />聽音樂
  <input type="button" name="button" id="button" οnclick="checkbox()" value="提交" />
  <select value="d" id="select">

  </select>

效果圖

打開狀態

提交後

select中顯示選中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章