How can I receive names via a text field in an HTML page and save them to an array in the browser’s Local Storage?

Asked

Viewed 250 times

1

I need help finishing function logic:

<form name="form1" onsubmit="submeter()">

    Nome: <input type="text" id="nome" value="" onkeyup="validarNome()"/><br/><br/>
    Idade: <input type="text" id="idade" value="" onkeyup="validarIdade()"/><br/><br/>
    <input type="submit" value="Salvar" onclick="salvar()"/><br/><br/>

</form>

<script>
    function salvar(){
        var Nomes = new Array();
        Nomes[i] = document.getElementById("nome").value;

    localStorage["Nomes"] = JSON.stringify(Nomes);
    }
</script>
  • 1

    Describe your problem/need better.

  • I need a javascript code that saves all name data into one vector and the age data into another vector in Local Storage. And that when making a new registration, the old data are not erased, but accumulated in the vector.

2 answers

1


You have to prevent form do Ubmit to the server. You can do this with <input type="submit" value="Salvar" onclick="return salvar()" /> in HTML and having return false; at the end of the function salvar.

Otherwise your code was almost there. A more flexible version, where you will find and save all fields that have the attribute name would be so:

function salvar() {
    var inputs = [].slice.call(document.querySelectorAll('form input[name]'));
    var data = {};
    inputs.forEach(function(input) {
        data[input.name] = input.value;
    });
    localStorage.meusDados = JSON.stringify(data);
    document.querySelector('form').reset();
    return false;
}

jsFiddle: https://jsfiddle.net/xaveqfax/

  • thanks, but I wanted the information to be accumulated in vector, and do not erase as soon as save a new data.

  • @Pedro this is simple, so you want an array/vector where each input is an object with the input data you have?

  • Yes. An array that will accumulate all names and another that will accumulate all ages.

  • I need a javascript code that saves all name data into one vector and the age data into another vector in Local Storage. And that when making a new registration, the old data are not erased, but accumulated in the vector. Could do please?

  • @Peter then you want something like this: https://jsfiddle.net/j5chv3r2/

0

var fs = require('fs');

var file = fs.createWriteStream('array.txt');
file.on('Erro', function(err) { /* houve um erro */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();

or

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ')).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok' }
);
  • I think what the author of the question (AP) is looking for is a solution in the browser, not in Node.js

  • Ai complica :3.

  • @Klanpaia localStorage would not be to simplify?

Browser other questions tagged

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