2011-06-05 80 views
17

我有一个输入字段:如何使输入字段只读,但仍然有数据发送回表单?

<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" /> 

我希望字段显示我的形式,但不希望用户能够编辑的字段。当用户点击提交时,我希望表单值被发送回服务器。

这是可能的。我尝试了disabled = "disabled",readonly = "readonly"的不同组合。似乎我总是得不到任何回报的领域。

回答

41

添加具有相同的名称将隐藏字段发送当表单提交的数据。

<input type="hidden" name="my_name" value="blablabla" /> 
<input type="text" name="my_name" value="blablabla" disabled="disabled" /> 
+0

谢谢。这很好。救了我...... :-) – UCC 2011-06-05 09:12:18

+4

这根本不起作用。如果禁用,则不会使用表单提交。相反,您将需要使用只读。 – Donato 2014-10-16 19:33:27

+3

@DanStayntouch禁用的字段不会发送隐藏的数据。 – Petah 2014-10-17 00:13:48

0

在提交只读字段时,您应该考虑使用输入type =“hidden”。否则,如果您仍然需要输入字段的值可见,则应该使用不同的名称创建另一个输入(type = text)。

<input cid="Topic_Created" name="Topic.Created" type="hidden" value="6/5/2011 8:22:45 AM" /> 
<!--This is visible: --> 
<input cid="Topic_Created" name="doesntmatter" size="25" type="text" value="6/5/2011 8:22:45 AM" /> 
3

在假设你使用一个脚本来创建表格,我建议使用<input type="hidden" />将提交变量与形式,但也可以使用常规的<input type="text" readonly="readonly" />显示变量给用户。这显然不会提交数值,但使其可见(而hidden输入将提交的值,但不是显示的值)。

你也可以用JavaScript做到这一点:

var theForm = document.getElementsByTagName('form')[0]; 
var inputs = document.getElementsByTagName('input'); 

for (i=0; i<inputs.length; i++){ 
    if(inputs[i].type == 'hidden'){ 
     var newInput = document.createElement('input'); 
     newInput.type = 'text'; 
     newInput.setAttribute('disabled'); 
     newInput.value = inputs[i].value; 
     theForm.appendChild(newInput); 
    } 
} 

Clumsy JS Fiddle demo

1

或者ü可以使用JavaScript一点操纵,表单提交之前

<form action="target.php" method="post"> 
<input type="text" id="anu" name="anu" value="data anu" disabled="disabled" /> 
<button onclick="document.getElementById('anu').disabled=''">send</button> 
1

随着Chrome浏览器在Windows 10只是一个具有名称=“your_name”和只读属性工作正常移除已停用的属性:客户端不能更改一个值,但它被发送到服务器。

相关问题