Output a JavaScript variable in an HTML input

Par ,
Publié le December 24, 2019
Logo HTML 5Logo JavaScript (JS)

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.

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">
var myvalue = "Hi";
document.getElementById('field1').setAttribute('value', myvalue);

Here is the output :

Method 2 : use write to output the HTML tag with the input.

var message = 'How are you doing ?';
document.write('<input type="text" value="' + message + '">');

Which give us :

Poster un Commentaire

Notify of