Search code examples
htmlinputtextuser-input

Write down user input in a text file


i tryed it with a basic html code like :

  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" value="Submit">
</form>

but then the input is saved like fname=John&lname=Doe

I wrote a script in python that gets the file xxx/xxx/display.txt when i use the basic html input function, the text will get saved as fname =john & sname=rober what i woud need is the string to get saved as john rober

how can i write the input down in the txt file without = and & , and how do i save it in the file, while overwriting everything previus in the txt file?


Solution

  • For that you need your js-code to be server side. I'd reccoment Node.js for that.

    Than we need to format the input with js:

    // Requiring fs module in which writeFile function is defined:
    const fs = require('fs');
    
    var fname = document.getElementById("fname").value;
    var lname = document.getElementById("lname").value;
    var fullname = fname + lname;
    
    // data which will write in a file
    let data = fullname;
    
    // Write "data" in "file.txt":
    fs.writeFile('file.txt', data, (err) => {
        // In case of an error trhow err:
        if (err) throw err;
    })