
方法有两种。
第一种通过<select>的属性来设置选中项,此方法可以在动态语言如php在后台根据需要控制输出结果。
<select id = "sel" >
<option value = "1" >1</ option >
<option value = "2" selected = "selected" >2</ option >
<option value = "3" >3</ option >
</ select >
第二种为通过前端js来控制选中的项:
<script type = "text/javascript" >
function change(){
document.getElementById("sel")[2].selected=true
}
</ script >
<select id = "sel" >
<option value = "1" >1</ option >
<option value = "2" >2</ option >
<option value = "3" >3</ option >
</ select >
<input type = "button" value = "修改" onclick = "change()" />
获取<select>标签选中项文本的js代码为:
var val = document.all.Item.options[document.all.Item.selectedIndex].text
var i=document.getElementById('sel').options[document.getElementById('sel').selectedIndex].value
扩展资料
Radio 对象代表 HTML 表单中的单选按钮。在 HTML 表单中 <input type="radio">每出现一次,一个 Radio 对象就会被创建。
单选按钮是表示一组互斥选项按钮中的一个。当一个按钮被选中,之前选中的按钮就变为非选中的。当单选按钮被选中或不选中时,该按钮就会触发 onclick 事件句柄。您可通过遍历表单的 elements[] 数组来访问 Radio 对象,或者通过使用 document.getElementById()。
参考资料:百度百科-radio
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />
<title>New Web Project</title>
<script src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
window.onload= function(){
var inpt= document.getElementById('myForm').getElementsByTagName('input') //获取表单下所有的input元素
for(var i=0i<inpt.lengthi++){ //遍历获得的input元素
if(inpt[i].type=='radio'){ //如果是单选按钮
if(inpt[i].defaultChecked) //页面载入时选中的值
document.getElementById('text1').value=inpt[i].nextSibling.nodeValue//显示页面载入时选中的值
inpt[i].onclick=function(){ // input的单击事件
if(this.checked)
document.getElementById('text2').value=this.nextSibling.nodeValue//显示被选中的值
}
}
}
}
// 下面是用jquery实现
$(document).ready(function(){
$('input:radio').each(function(){
if(this.checked)
$('#text1').val($(this).val())
$(this).click(function(){
if(this.checked)
$('#text2').val($(this).val())
})
})
})
</script>
</head>
<body>
<form id="myForm">
<input type="radio" name="rad" checked="checked" value="音乐"/>音乐<br />
<input type="radio" name="rad" value="美术"/>美术<br />
<input type="radio" name="rad" value="电影"/>电影<br />
默认值:<input type="text" id="text1" /><br />
选中值:<input type="text" id="text2" />
</form>
</body>
</html>
name值一定要相同才能够单选,要默认选项,加一个属性checked就可以了。
如下:
<inputtype="radio"name="radio"value="1">单选1
<inputtype="radio"name="radio"value="2">单选2
<inputtype="radio"name="radio"value="3"checked>单选3
<inputtype="radio"name="radio"value="4">单选4
例如:
<input type="radio" name="identity" value="学生" checked="checked" />学生 <input type="radio" name="identity" value="教师" />教师 <input type="radio" name="identity" value="管理员" />管理员把三个 name 设置一样
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)