JS 获得 输入框 和 radio 的值
这几天遇到很蛋疼的事情。
有一个链接,要用到输入框输入的数据,和 radio 选中的值,作为参数。
但是,一直不知道怎么弄这个,查了一些资料,算是解决了这些问题。
先说说获得输入框的值。这里,我是用了struts 2 的标签
<struts:textfield name="username" label="账号" /〉
这样子要传用户输入的数据,结果发现,个人推荐用JS的方法。
先给它弄个id号,然后在JS里面调用document.getElementById
("username");
<struts:textfield name="username" label="账号" id="username"/>
接下去是一个最蛋疼的东西 获得radio里面的数据
刚开始,我是用这种方法写的,
<struts:radio list="#{'student':'学生','teacher':'教
师','manager':'管理员'}" name="type" id="type" ></struts:radio>
但是,发现一直不能在JS里面获得数据,于是,我只能投机取巧了。改用
了下面的写法
<input type="radio" name="type" value="student" id="student"/>学
生
<input type="radio" name="type" value="teacher" id="teacher"/>教
师
<input type="radio" name="type" value="manager" id="manager"/>管
理员
此处切记,name属性要和你在Action里面的属性type相同。就是Action里
面要有:
private String type;
这个属性
最后,就是JS的函数,按照id来取得数据。
下面是JS的函数代码;
<script type="text/javascript">
function forgetpassword()
{
var a = document.getElementById("username").value;
if(a=="" || a==null)
{
alert("用户名不能为空");
}
else
{
var b = document.getElementById("student");
if(b.checked)
{
window.location.href="ForgetPassword!execute.action?username=" + a + "&type=" + b.value;
}
else
{
b = document.getElementById("teacher");
if(b.checked)
{
window.location.href="ForgetPassword!
execute.action?username=" + a + "&type=" + b.value;
}
else
{
b = document.getElementById("manager");
if(b.checked)
{
window.location.href="ForgetPassword!
execute.action?username=" + a + "&type=" + b.value;
}
else
{
alert("请选择用户类型");
}
}
}
}
}
</script>
今天起床的时候,优快云的程序员给我介绍了另外一种方法,也是可以的,还是使用Struts 2 的标签的方法。(优快云就是强大啊。)试验过,很好,就采用这种方法了。
还是这一招:
<struts:radio
师','manager':'管理员'}" name="type" id="type" ></struts:radio>
然后,用下面这个语句,获得数组。
var b = document.getElementsByName("type"); (注意:这里是getElementsByName,Element后面有个s的,如果没有s,好像就一直返回第一个radio的值。感觉很像C++ 或 Java 里面的数组。
下面是JS函数:
<script type="text/javascript">
</script>