How to pass text as a parameter to a JavaScript function?

1

I need to do a JavaScript function and I want it to receive the parameters in text format:

HTML code:

<button onClick="AlteraNome(Felipe)">Enviar Nome</button>

JavaScript code:

function AlteraNome(nome){
   document.write(nome);
}

If someone can help me, thank you!

    
asked by anonymous 12.12.2015 / 01:25

1 answer

1

If you are trying to get the name applied to the button in the question example, you can do this using document.getElementById("meuBotao").innerText; as follows:

function alteraNome() {
    // procura o id="meuBotao" e substitui o texto dentro dele por - "Outro Nome Aqui"
    document.getElementById("meuBotao").innerText="Outro Nome Aqui";
}
<button onclick="alteraNome()" id="meuBotao">Altera Nome do Botão</button>

If you are trying to get a name entered in a input and pass it elsewhere, like another div for example, you can do it as follows:

function transfereNome() {
    var input = document.getElementById('enviaNome')
    var div = document.getElementById('mostraNome');
    // diz que o conteúdo dentro do id="mostraNome" é igual ao valor introduzido no input
    div.innerText = input.value;
}
<input type="text" id="enviaNome"/>
<button onclick="transfereNome()">Enviar Nome</button>
<div id="mostraNome"></div>
    
12.12.2015 / 02:44