How to pass input value to Javascript function

Asked

Viewed 28,857 times

0

How to pass values of other inputs (as a parameter) for a function that will only be executed on a given input?

<input id="nome" type="text" value="LocalHost"/>
<input id="email" type="email" value="[email protected]"/>
<input id="tel" type="tel" onChange="funcao()" value="(62)90000-0000"/>

Javascript:

function funcao(nome, email, telefone) {
   // valor do type="text", type="email" e type="tel"
}

Observing:

The inputs are inside a foreach:

<?php foreach($resultado as $res){?>
    <input id="nome" type="text" value="<?php echo $res['nome']; ?>"/>
    <input id="email" type="email" value="<?php echo $res['email']; ?>"/>
    <input id="tel" type="tel" onChange="funcao()" value="<?php echo $res['telefone']; ?>"/>
<?php } ?>
  • document.getElementById("nome").value;...

  • @Magichat, I need these values to be passed as function parameter...

2 answers

2


You can create an intermediate function to handle the event and pass the values to your function.

Something like that:

<head>
  <script>
    function onChangePhone(e) {
      var nome = document.getElementById('nome').value;
      var email = document.getElementById('email').value;
      var tel = document.getElementById('tel').value;
      funcao(nome,email,tel);
    }

    function funcao(nome, email, telefone) {
       console.log("Nome: " + nome);
       console.log("E-mail: " + email);
       console.log("Telefone: " + telefone);
    }
  </script>
</head>
<body>
  <input id="nome" type="text" value="LocalHost"/>
  <input id="email" type="email" value="[email protected]"/>
  <input id="tel" type="tel" onchange="onChangePhone()" value="(62)90000-0000"/>
</body>

But this specifically answering your question of how to send the values of three inputs as function parameters funcao. I don’t know the logic you want to apply, but you can probably use one function only. Something like this:

<head>
  <script>
    function funcao(e) {

      var nome = document.getElementById('nome').value;
      var email = document.getElementById('email').value;
      var telefone = document.getElementById('tel').value;

       console.log("Nome: " + nome);
       console.log("E-mail: " + email);
       console.log("Telefone: " + telefone);
    }
  </script>
</head>
<body>
  <input id="nome" type="text" value="LocalHost"/>
  <input id="email" type="email" value="[email protected]"/>
  <input id="tel" type="tel" onchange="funcao()" value="(62)90000-0000"/>
</body>

Only one correction: the native javascript event is lowercase (Docs). Then the right thing would be onchange instead of onChange, in which some browsers understand both versions.

EDITED (after question update)

First thing, you can’t have more than one identical ID on the same page, that is, the ID’s should be unique. In your loop, you’re assigning the ID’s nome, email and telefone to more than one element.

So in this case, a possible solution is replace Ids with a class (to refer them later), and group them (this part is important) into one parent element classy dados.

Another thing, your question code is in trouble (php code mixed with html), but it may have been at the time of copy/paste.

I put some comments in javascript to explain what is happening at each step. These ways to get the event and the target are very popular and unfortunately are necessary to have a maximum compatibility.

There are libraries like jQuery that facilitate these operations, but it is your decision whether you want to include it or not, and evades the scope of the question.

Here is the code:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script>
        function mudouTelefone(event) {
            /* 
                como você está usando javascript puro (vanilla),
                você tem que fazer alguns truques para manipular o objeto evento.
                Dependendo do navegador, ou ele vem como parâmetro da função, ou
                encontra-se como propriedade do objeto window.

            */  
            event = event || window.event;


            /* 
                a mesma coisa aqui. O alvo (target) do evento (ou seja, o elemento que foi clicado)
                pode vir como propriedade .target ou como propriedade .srcElement, a depender do navegador
            */
            var target = event.target || event.srcElement;

            /* pegamos a referência do pai, para depois procurar os filhos dele */
            var divDados = target.parentNode;

            /* procuramos os elementos dentro do pai divDados com o método .querySelector */
            var nome = divDados.querySelector('.nome').value;
            var email = divDados.querySelector('.email').value;
            var tel = divDados.querySelector('.tel').value;


            funcao(nome,email,tel);
        }

        function funcao(nome, email, tel) {
           console.log("Nome: " + nome);
           console.log("E-mail: " + email);
           console.log("Telefone: " + tel);
           alert("Nome: " + nome + ", E-mail: " + email + ", Telefone: " + tel);
        }
    </script>
</head>
<body>
<?php foreach($resultado as $res){ ?>
    <div class="dados">
        <input class="nome" type="text" value="<?php echo $res['nome']; ?>"/>
        <input class="email" type="email" value="<?php echo $res['email']; ?>"/>
        <input class="tel" type="tel" onchange="mudouTelefone(event)" value="<?php echo $res['tel']; ?>"/>
    </div>
<?php } ?>


</body>
</html>

One last tip: if you got confused with the operator ||, has a reply here at Sopt that explains well its operation.

EDITED 2 (after the OP has shown the current code)

Based on your code posted in Pastebin, I realized that it was not the same structure shown in the example, and this influenced the response. The strategy I suggested was to group your inputs into a tag that would be the common element of all. Then just call the parentNode that he would find the parent element (that we put the class dados), and from it you would locate the children.

But in its actual code, the element in common with its inputs is two layers above <tr />, that is, the table row. To work, you must add a .parentNode at the .parentNode for him to climb two layers in the DOM. Something like this:

function ultimaNFe(event) {
    event = event || window.event;
    var target = event.target || event.srcElement;
    /* pegamos a referência o elemento em comum, no caso, dois nodes acima (a linha da tabela) */
    var trNode = target.parentNode.parentNode;

    /* procuramos os elementos dentro do tr com o método .querySelector */
    var id_emp = trNode.querySelector('.id-emp').value;
    var ultima_nfe = trNode.querySelector('.ultima-nfe').value;
    funcao(id_emp,ultima_nfe);
}

This way you can remove the div dados. Would look like this: http://pastebin.com/3Tr4kQ00

1

I don’t think that’s the best way to do it:

<head>
        <script>
            function funcao(nome, email, telefone) {
                alert("nome: " + nome +" email: "+ email +" telefone: "+ telefone);
            }
        </script>
</head>
<body>
    <form>
        <input id="nome" type="text" value="LocalHost"/>
        <input id="email" type="email" value="[email protected]"/>
        <input id="tel" type="tel" onChange="funcao(nome.value, email.value, tel.value)" value="(62)90000-0000"/>
    </form>

</body>

http://jsfiddle.net/aWSSV/19/

Abs

  • a truth, nor need getelement... good

  • Hello Renato, my alert is returning undefined. @Renatoserra

  • Or should I say: when performing debug: name, email and phone are undefined

  • strange here is bringing normal, I tested now on Chrome, this in which browser?

  • Google Chrome. You can publish to Jsfiddle?

  • Coloqueii la http://jsfiddle.net/aWSSV/19/

  • Renato, do you accept the invitation to chat? http://chat.stackexchange.com/rooms/52185/como-passar-valor-de-input-para-funcao-javascript @Renatoserra

Show 2 more comments

Browser other questions tagged

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