Support code.broker and free tutorials by clicking on this ad above ⬆

Pre-populate a form field (input) with JavaScript

Logo HTML 5 HTML 5
Logo JavaScript (JS) JavaScript (JS)

By ,
Published on 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 :

Poster un Commentaire

avatar
  Subscribe  
Notify of

Did you like this tutorial ? Click on this ad below ⬇ to support code.broker