Pre-populate a form field (input) with JavaScript
Par arthur-and-ashes,
Publié le December 24, 2019
Today, I need to get the information stored in a cookie to add it to an HTML input. Then, when a user tries to contact me, a hidden field will give me more information on his visit.
Of course, it would be easier to get this cookie with PHP and to add the content in an HTML field. But as I coded my cookie in JavaScript, I prefer to continue with this language. So I will try to pre-populate a field of my form with JavaScript.
It is quite easy to display HTML values in a form input. I will use a text input in this tutorial, but normally I definitely use a “hidden” field.
<input type="text" id="myfield" />
Method 1 : use setAttribute
<input id="field1"> <script> var myvalue = "Hi"; document.getElementById('field1').setAttribute('value', myvalue); </sript>
Here is the output :
Method 2 : use write to output the HTML tag with the input.
<script> var message = 'How are you doing ?'; document.write('<input type="text" value="' + message + '">'); </script>
Which give us :