<html>
<head>
<title></title>
<script>
select2str=function(id)
{
var obj=document.getElementById(id);
var destobj=document.getElementById(id.replace("sel_",""));
var strValue="";
for( var i=0; i<obj.options.length; i++)
{
if( obj.options[i].selected)
{
strValue+=obj.options[i].value+",";
}
}
strValue=strValue.substring(0,strValue.lastIndexOf(','));
destobj.value=strValue;
alert(strValue);
}
bindselect=function(id,strvalue)
{
var obj=document.getElementById(id);
var strs=strvalue.split(",");
for( var i=0; i<obj.options.length; i++)
{
if( isinarray(obj.options[i].value,strs))
{
obj.options[i].selected=true;
}
}
}
isinarray=function(value,arr)
{
for(var i=0; i<arr.length; i++)
{
if(value==arr[i])
{
return true;
}
}
return false;
}
</script>
</head>
<body>
<select id="sel_cate" size="3" multiple >
<option value="1">x1</option>
<option value="2">x2</option>
<option value="3">x3</option>
<option value="4">x4</option>
</select>
<script>
bindselect('sel_cate','1,4');
</script>
<input type="text" id="cate" name="cate" />
<input type="button" id="btnSure" name="btnSure" onclick="select2str('sel_cate')" />
</body>
</html>
本文介绍了一种使用JavaScript实现的选择器与输入框值同步的方法。通过定义`select2str`函数来获取选中项的值,并将其设置为指定文本框的内容;同时,通过`bindselect`函数可以预先设置选择器的选中项。此方法适用于需要将用户的选择转换为字符串进行后续处理的场景。
764

被折叠的 条评论
为什么被折叠?



