How to set default value in a form through javascript?

Asked

Viewed 957 times

0

I would like to set a default value in a certain field of a form through javascript. Let’s assume that the id of the field is #code.

  • Please, for better help, please put your html code here.

3 answers

4


You can call a tag script in your html;

<script>
    (function(){
        document.getElementById('idDoCampo').value = 'Valor Padrão';
    })();
</script>

this will work for tags input of the kind text.

Or simply:

<input type="text" id="idDoCampo" value="Valor Padrão"/>

4

// JS Puro
document.getElementById('codigo').value = "Teste"

// jQuery
$('#codigo').val('Teste 2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="codigo" name="codigo" type="text" />

2

You can do it this way:

<input type="text" value="" id="codigo" >
<script>
document.getElementById("codigo").value = "Meu código";
</script>

It takes the element using getElementById and arrow its 'value'.

Upshot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.