Why doesn’t my javascript work?

Asked

Viewed 931 times

1

Why doesn’t it work ? I’m a few minutes trying to understand and follow 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)
};
  • It depends. How are you "running"/calling this code this code? You are importing this JS code into an HTML file or it is inside the HTML itself.

  • is inside the HTML code, I am now starting to study javascript

  • 4

    What result are you hoping to get when running this code? Could [Edit] the question with this information?

2 answers

4


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

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

This piece has no problems. Calling mostra(algo) he’s going to print that algo.

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

Here’s a bug you’re deleting the element name #nome, I think what you want is to read that value, not erase it. If you want this function to return that nome you should wear it like this: return document.getElementById("nome").value;, and when the function is called returns the value of that element.

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

Here’s a problem. You have to invoke the function pegaNome with parentheses otherwise she won’t run... you can use mostra(pegaNome());.

function meubotao(){
    (escreveDados)
};

Here’s a problem, like the previous one. To invoke a function you have to use (). Nese case is unnecessary means the function meubotao because it only calls the other. I would remove... but if you want to use, then in view of (escreveDados) you must use escreveDados();

1

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

Make sure pegaNome() return any string to debug before trying to fetch an element value.

Another thing that is wrong in your code is that by passing the lambda pegaNome for mostra(), it needs to be triggered using () at a time, either on call or internally on mostra as I inserted 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();
  • 1

    could show me an example?

  • insert the example

Browser other questions tagged

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