How can I receive names through a text field in an HTML page and save them to a vector in the browser's Local Storage?

0

I need help completing the 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>
    
asked by anonymous 23.07.2016 / 06:18

2 answers

1

You have to prevent form from submitting 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 fetch and save all fields that have the name attribute would look like this:

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: link

    
23.07.2016 / 07:06
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' }
);
    
23.07.2016 / 06:26