Search code examples
javascripthtmlweb

how do I enter a string into a field with a button?


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.


Solution

  • 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