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

Asked

Viewed 2,187 times

2

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 anyone can help me, I’d appreciate it!

  • I suppose you want to take the value from a input right? Click [Edit] and add your form.

  • 3

    Or if you want to pass a fixed text, you can put it between apostrophes (onClick="AlteraNome('Felipe');")

1 answer

2


If you are trying to get the name applied to the button in the example of your question, 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’re trying to get a name entered in a input and pass it somewhere else, like another div for example, you can do it this way:

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>

  • 2

    Note: These examples do not work in Firefox < 45 (innerText is not supported). You could use textContent, but the same does not work in IE < 9, and does "strange" things with whitespace. See that post (in English) for more details.

Browser other questions tagged

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