Why does not my javascript work? [closed]

1

Why does not it work? I am a few minutes trying to understand and follows the code:

//funçao de document write
var mostra = function (frase){
    document.write(frase)
};


// pegar elemento
var pegaNome = function (){
    document.getElementById("nome").value="";
};


var escreveDados = function(){
    mostra(pegaNome)
};

function meubotao(){
    (escreveDados)
};
    
asked by anonymous 22.06.2015 / 20:42

2 answers

4

Your code has some errors, I'll comment and hope it helps.

//funçao de document write
var mostra = function (frase){
    document.write(frase)
};

This piece has no problems. Calling mostra(algo) it will print this algo .

// pegar elemento
var pegaNome = function (){
    document.getElementById("nome").value="";
};

Here you have an error you are deleting the name of the element #nome , I think what you want is to read this value, not delete it. If you want this function to return this nome you should use this: return document.getElementById("nome").value; , and when the function is called it returns the value of that element.

var escreveDados = function(){
    mostra(pegaNome)
};

Here you have a problem. You have to invoke the pegaNome function with parentheses otherwise it will not run ... you can use mostra(pegaNome()); .

function meubotao(){
    (escreveDados)
};

Here you have a problem, similar to the previous one. To invoke a function you must use () . In this case the meubotao function is unnecessary because it only calls the other. I would remove ... but if you want to use, then instead of (escreveDados) you should use escreveDados();

    
22.06.2015 / 22:04
1

pegaNome() does not return a string that you expect to print in mostra() .

Make pegaNome() return any string for debugging before attempting to fetch an element value.

Another thing that is wrong with your code is that by passing lambda pegaNome to mostra() , it needs to be fired using () at a time, either in the call or internally in mostra as I entered in the example below.

Example:

var mostra = function (frase) {
    document.write(frase)
};

var pegaNome = function () {
    //document.getElementById("nome").value;

    return 'Foo';
};

var escreveDados = function() {
    mostra(pegaNome())
};

escreveDados();
    
22.06.2015 / 20:46