0

I am new here pls correct me if I do something wrong. I couldn't find a solution for this simple issue, yet. So I am trying to programm a field where I can enter any text and a button to submit it. When I click on the button the text should be displayed in an other div.

That's what I've programmed so far: Field + Button:

                            <form>
                                <div>
                                  <input name="snfield" type="text" id="snfield" value="any text" maxlength="20" minlength="1" required> 
                                  <button onclick="addnewSN('snfield')"><label id="labelsn" for="snfield">Enter Serialnumber</label></button>
                                </div>
                            </form>

Script:

        function addnewSN(text) {
            document.getElementById('sn').innerHTML += text;
            
        }

Div for displaying the text:

<div id="sn"></div>

When I click on the button the site reloads and the div is empty.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
hanlok
  • 11
  • 4

3 Answers3

1

simplest is to return false from the button onclick code, i.e. onclick="addnewSN('snfield'); return false;" adding onsubmit="return false;" to the form would also work in this snippet as it stands, but may not always be desirable

timchessish
  • 136
  • 5
0

Or, in other way

  1. Remove onclick handler
  2. Add handler like this
document.getElementById('target-button').addEventListener('click', function (event) {
    event.preventDefault();
    // find input
    // get value from it
    document.getElementById('sn').innerHTML += 'value';
});
Maxick
  • 68
  • 6
  • 1
    Hello Maxick, sorry but I was not able to implement your solution, but the both other solutions worked. Thank you very much for your help! – hanlok May 17 '23 at 10:06
0

You are passing input id to the function, not the input text.
First get the value from input id and add it to 'sn'

function addnewSN(id) {
  const inputText = document.getElementById(id).value
  document.getElementById('sn').innerHTML += inputText;
}
  • Thank you very much Blerton! This worked perfect, but I had to add the solution of timchessish aswell so that the text stays and does not disapear after milliseconds again. – hanlok May 17 '23 at 10:01