0

I have this script performed on submit:

function analyze() {
    var answer = document.forms["questions"]["answer1"].value;
    var item = document.getElementById("content");
    item.innerHTML=answer;
}

Script is performed, but div doesn't keep the value, it changes back.

fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
harry
  • 25
  • 7

3 Answers3

0

When you do a submit, your page is going to re-render, causing all of your elements to get back to their initial state. So changing the your div or whatever you have in the HTML with class content is going to reset to being back to being blank.

You probably want to save the answer in Browsers LocalStorage or some sort of data structure and then request it out of there.

Dragomir Kolev
  • 1,088
  • 10
  • 25
0

Save your answer value to localStorage or sessionstorage and then show the same value in your div. If you are submitting form then it will re-load the page and clear the innerHTML of div.

0

A submit button causes the page to rerender. You have a number of options to prevent that:

  1. Don't use a submit button, use a normal button that happens to SAY submit. You would then run the function "onClick" for the button, not "onSubmit" for the form. (this is what I recommend)
  2. Return false from that function and/or call PreventDefault.
  3. Actually submit it to the server and have the server do the work and return the page (probably not a good choice for performance reasons).
  4. EDIT: you could do something with local or session storage, but that seem a bit rube-goldburg for the problem you have.
A Hettinger
  • 448
  • 2
  • 11
  • I added return false at the end of this function, but its behavior the same. – harry Aug 24 '17 at 15:13
  • returning false only works if it actually reaches the return. It's pretty brittle; any exceptions or errors could prevent it from reaching the return. There is a reason I recommend using a non-submit button here. – A Hettinger Aug 24 '17 at 15:48