Get the value of an input with javascript

4

I'm doing a PivotTable where the data comes from the database, and the user has the ability to edit that data. This data coming from the database is within <div> .

Next to this data has a Editar button where it changes the tag <div> by a <input> , and another button Salvar appears, so far everything is right.

But when I click save it calls a function, where it gets the value of this <input> to update, only it is taking the old value, not the new one.

I want to know how to get this new data that the user typed.

Here is the code:

function Editar(){
    //armazena o elemento div em uma variavel
    var data = document.getElementById('data');
    //muda a div para um campo, onde o usuario digita uma nova data
    data.innerHTML = "<input type='text' name='data' value='" + data.innerHTML +"' id='dataVal'>";
    //armazena a data digitada na variavel
    dataVal = document.getElementById('dataVal').value;
}

function Salvar(){
    console.log(dataVal);
}

So instead of giving me the new date, it returns the old date.

    
asked by anonymous 16.08.2014 / 05:12

2 answers

5

Your variable dataVal seems to me to be in the global scope, since I do not see it being declared. It would be best to avoid this.

Your problem here is that dataVal = document.getElementById('dataVal').value; saves the value of this input at the moment. That is, dataVal is a variable that holds a static value, what you want is to eventually save a reference (a pointer) to the element, ie only: dataVal = document.getElementById('dataVal'); .

In your first Edit function (and note that as a rule you write functions with small print and large print classes) you could take the last line.

My code suggestion would be:

function editar(){  // com "e" pequeno para seguir as boas práticas
    //armazena o elemento div em uma variavel
    var data = document.getElementById('data');
    //muda a div para um campo, onde o usuario digita uma nova data
    data.innerHTML = "<input type='text' name='data' value='" + data.innerHTML +"' id='dataVal'>";
}

function salvar(){  // "s" pequeno
    // busca a data digitada na variavel
    var dataVal = document.getElementById('dataVal').value;
    console.log(dataVal);
}
    
16.08.2014 / 09:13
2

In the Save function try to place:

     document.getElementById('dataVal').value;

Instead of the variable.

    
16.08.2014 / 07:43