How can I make an input field read only but still have it send data back to a form?

后端 未结 7 1298
情书的邮戳
情书的邮戳 2021-01-01 11:22

I have an input field:


相关标签:
7条回答
  • 2021-01-01 12:04

    You can add 'readonly'='true' in the input element. With this the user cant edit and also send the value back to the server.

    <input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" readonly='true' />
    
    0 讨论(0)
  • 2021-01-01 12:07
    <script type="text/javascript"> 
        function myFn(event) { 
            event.stopPropagation(); event.preventDefault(); 
        } 
    </script> 
    
    <input onkeydown="myFn(event)" >
    
    0 讨论(0)
  • 2021-01-01 12:08

    On the assumption you're using a script to create the form, I'd suggest using <input type="hidden" /> which will submit the variable with the form, but also use a regular <input type="text" readonly="readonly" /> to show the variable to the user. This won't submit the value, obviously, but will make it visible (while the hidden input will submit the value, but not show the value).

    You could also do this with 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.

    0 讨论(0)
  • 2021-01-01 12:11

    alternatively u can make a little manipulation with javascript, remove the disabled property before form submitted

    <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>
    
    0 讨论(0)
  • 2021-01-01 12:13

    Adding a hidden field with the same name will sends the data when the form is submitted.

    <input type="hidden" name="my_name" value="blablabla" />
    <input type="text" name="my_name" value="blablabla" disabled="disabled" />
    
    0 讨论(0)
  • 2021-01-01 12:19

    With Chrome browser on Windows 10 just having name="your_name" and the readonly attributes works fine: client cannot change a value, but it is sent to the server.

    0 讨论(0)
提交回复
热议问题