全屏浏览
缩小浏览
回到页首

web基础----->readonly与disabled的区别

  readonly和Disabled是用在表单中的两个属性,它们都能够做到使用户不能够更改表单域中的内容。但是它们之间有着微小的差别,今天我们通过案例来学习一下。

 

readonly和Disabled的区别

一、 我们在index2.jsp中加入以下代码:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript">
    function enabled() {
        document.myform.username.disabled = false;
    };
    function readonly() {
        document.myform.password.readOnly = false;
    };
</script>
</head>
<body>
<form action="servlet/LoginServlet" method="get" name="myform">
    username: <input type="text" value="Linux" name="username" disabled="disabled" /> <br>
    password: <input type="text"  name="password" value="123456"  readonly="readonly" > <br>   
    age: <input type="text" value="22" name="age" /> <br>
    address: <input type="hidden" value="china" name="address" /> <br>
    <input type="submit" value="submit"> 
</form>
    <button onclick="readonly()">readonly</button>
    <button onclick="enabled()">enabled</button>
</body>
</html>

注意document.myform.password.readOnly的only中的o是大写的,如果小写则没有效果。

 

二、 在servlet中仅仅是获取数据操作

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username = request.getParameter("username");
    response.getWriter().println("username: " + username);
    
    String age = request.getParameter("age");
    response.getWriter().println("age: " + age);
    
    String password = request.getParameter("password");
    response.getWriter().println("password: " + password);
    
    String address = request.getParameter("address");
    response.getWriter().println("address: " + address);
}

 

三、 运行效果如下:

 

 四、 总结readonly、disbled和hidden

  • readonly只针对input和textarea有效,而disabled对于所有的表单元素都有效,包括select, radio, checkbox, button等。
  • 表单元素在使用了disabled后,当我们将表单以POST或GET的方式提交的话,这个元素的值不会被传递出去,而readonly和hidden会将该值传递出去
  • 两者的数值改变,只能通过script脚本。

详情请参见w3c文档:https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.12

 

posted @ 2016-06-02 17:14  huhx  阅读(1366)  评论(0编辑  收藏  举报