<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>
php和javascript用selectedIndex多选项显示在页面上
最新推荐文章于 2023-07-09 09:38:20 发布