Menu Close

How to append data to div element using JavaScript

0
(0)

To append form submit data to any <div> or <section> element we need to use manipulation techniques. Initially we need to create one empty div element where we can append the data. Then we can append the entered input value to the inner text of that specific div by using the simple JavaScript codes.

Here, I share the code snippet for simple data append model with example.

<form> 
    <div class="form-group">
        <div class="input-group mb-2">
            <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroup-sizing-default">Enter Input</span>
            </div>
            <input type="text" class="form-control" id="e_input">
        </div>
    </div>

    <div class="form-group text-center"> 
        <button id="add-data" class="btn btn-primary btn-lg" type="button"> 
            Add Name 
        </button> 
    </div> 
</form> 

<h3>List of Data:</h3> 
<div id="mydata"></div>

<script> 
    function append_to_div(div_name, data){ 
        document.getElementById(div_name).innerText += data; 
    } 

    document.getElementById("add-data") 
            .addEventListener('click', function() { 
        var e_input = document.getElementById("e_input"); 
        var value = e_input.value.trim(); 

        if(!value){
            alert("Input field can't be empty!"); 
        } else {
            append_to_div("mydata", value+"\n"); 
        }
        e_input.value = ""; 
    }); 
</script> 

Output

Enter Input

List of Data:

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Share

Posted in HTML, JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

You can also read...