Getting data from a form to use in JavaScript (no php)


#1

I want to collect some user input, edit it and output it to the DOM. I have skeleton code that works, but after executing, the page reloads and the data added to the DOM has gone. There’s a codepen here:

Later I shall be generating html around the data the user submits.

Where am I going wrong here?

Thanks
Roy

PS I am aware of security issues - this is for me to use on my own PC only, to generate index pages for a portfolio.


#2

Hi @roygrubb, the button element defaults to type="submit"; so you might just add a type="button" attribute to stay on the page. Alternatively, you can prevent the form from getting submitted by calling event.preventDefault():

var form = document.getElementById('frm1')

form.addEventListener('submit', function (event) {
  event.preventDefault()
  getData()
})

(Remove the onclick attribute from the button then – mixing JS and HTML is not a good idea anyway…)


#3

Thank you for the answer, and for two valuable additional lessons.


closed #4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.