1. 程式人生 > 其它 >php和javascript用selectedIndex多選項顯示在頁面上

php和javascript用selectedIndex多選項顯示在頁面上

技術標籤:php學習筆記phpjsjavascript

<html>
<head>
<meta http-equiv="content-type" content="text/html charset=uft-8"/>
<title></title>
</head>
<body>
<form method="post" action="" id="form1">
<table width="300"
border="0" cellpadding="0" cellspacing="0"> <tr> <td height="30" align="center" valign="middle">請選擇你喜歡的php類圖書</td> </tr> <tr> <td align="center" valign="middle"><select name="select[]"
size="5" multiple onchange="change()"> <option value="PHP程式開發範例寶典" >PHP程式開發範例寶典</option> <option value="PHP5從入門到精通">PHP5從入門到精通</option> <option value="PHP函式參考大全">PHP函式參考大全</option> </select> </tr>
<tr> <td height="30" align="center" valign="middle" ><input type="submit" name="submit" value="提交"></td> </tr> </table> </form> <p id="p1"></p> <?php //用php輸出選中項的值 if($_POST['submit']=="提交"){ echo "你選擇的意見主題為:"; foreach($_POST['select'] as $value) echo $value."\n\n"; } ?> <script> function change(){ var form=document.forms[0]; var sel=form.elements['select[]']; sel.options[sel.selectedIndex].selected=true;  //設定選中項 var selectedOptions=getSelectedOptions(sel); var message=""; for(var i=0,len=selectedOptions.length;i<len;i++){  //出現選中項的索引、文字、和值 message+="selected index:"+selectedOptions[i].index+"\nselected text:"+selectedOptions[i].text+"\nselected value:"+selectedOptions[i].value+"\n\n"; } var p=document.getElementById('p1'); p.innerHTML=message; } function getSelectedOptions(selectbox){  //用for迴圈來選取被點中設定了selected的項,再壓縮到陣列中再返回 var result=new Array(); var option=null; for(var i=0,len=selectbox.options.length;i<len;i++){ option=selectbox.options[i]; if(option.selected){ result.push(option); } } return result; } </script> </body> </html>