skip to Main Content

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.

3

Answers


  1. 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';
    });
    
    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search