Take the value of an input with javascript

Asked

Viewed 12,072 times

4

I’m making a dynamic table where the data comes from the database, and the user has the possibility to edit this data. This data coming from the bank is inside <div>.

Next to these dice is a button Editar where it changes the tag <div> by a <input>, and another boot appears Salvar, so far all right.

Only when I click save it calls a function, where it picks up the value of this <input>to update, only he is taking the old and not the new.

I want to know how to get this new data that the user has 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.

2 answers

5


Your variable dataVal seems to me to be in the global scope because I do not see it being declared. It would be better to avoid that.

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

In its first function Edit ( and note that normally write functions with small letter and Classes with large letter) you could take the last line.

My suggested code 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);
}

2

In the role of Save tries to put:

     document.getElementById('dataVal').value;

In place of the variable.

Browser other questions tagged

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