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">
<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