How do I set default value in a form via javascript?

0

I would like to set a default value in a given field of a form via javascript. Let's assume that the field id is #code.

    
asked by anonymous 24.04.2018 / 14:40

3 answers

4

You can call a script tag in your html;

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

This will work for input tags of type text .

Or simply:

<input type="text" id="idDoCampo" value="Valor Padrão"/>
    
24.04.2018 / 14:43
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><inputid="codigo" name="codigo" type="text" />
    
24.04.2018 / 14:44
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 the 'getElementById' and arrows its 'value'.

Outcome

    
24.04.2018 / 14:43