Output command or pass output in php

Asked

Viewed 66 times

0

Hello.

I want to return the success message if a name is inserted into the array. And I want to display the names in that array.

I don’t want to use Alert(). Document.write doesn’t work well in functions, especially with events or timer functions. I have tested with timers and events, but other things appear on the screen and not what I want. Already with Alert() works. There is another output command?

Or maybe, I can use php to display the success message and array names. As a step from javascript to php?

Follow two javascript functions for such.

<script>
    j = 0;
    i = 0;

    nomes = new Array();

    function inserirNome() {
        nome = prompt("informe o nome");

        nomes[i] = nome;

        alert("Nome inserido");
        i++;
    }

    function verNomes() {

        while (j < i) {
            alert(nomes[j]);

            j++
        }

        if (i == 0) {
            alert("Não tem nome inserido");
        }

    }
</script>

<a onclick="inserirNome()"> Inserir um nome</a>

<a onclick="verNomes()"> Ver os nomes inseridos</a>

  • Here is functioning normally with the getElementById, including the document.write.

1 answer

0

Try this, it’s also a good way to print returns in the body of the document.

var nomes = [];
var div = document.getElementById('mensagem');

function inserirNome() {
  var nome = prompt('Insira o nome');
  if (nome) {
    if (nomes.push(nome)) {
      div.innerHTML = ('inserido: ' + nome);
    }
  }
}

function verNomes() {
  var nick = '',
    x = 0;
  nomes.forEach(function(nome) {
    nick += 'Nome' + x + ':' + nome + "<br/>";
    x++;
  });
  if (nick == '') {
    div.innerHTML = 'Nenhum nome encontrado';
    return;
  }
  div.innerHTML = nick;
}
<div id="mensagem"></div>
<a href="#" onclick="inserirNome()"> Inserir um nome</a>
<a href="#" onclick="verNomes()"> Ver os nomes inseridos</a>

  • Didn’t work to list names.

  • There was an error closing the tag div, reedited code, try it now.

  • Interesting solution Edilson +1... @Andrénascimento, click above on "Run code snippet" to see how it works...

Browser other questions tagged

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