1

I have A Form in HTML. Here's my Code:

    <div id="format">
         <form id="myForm" onsubmit="myForm(event)">
         <b>Name:</b></br>
         <input type="text" name="name" id="name"  required="required" ></input></br>
         <b>Phone Number:</b></br>
         <input type="phone" name="phone" id="phone"  required="required" ></input></br>
        <b>Birthday:</b></br>
        <input type="date" name="bday" id="bday" required="required" ></input></br>
        <b>Email:</b></br>
        <input type="email" name="email" id="email"  required="required" ></input></br>
        <b>Password:</b></br>
        <input type="password" name="pWord" id="pWord" required" ></input></br>
        <button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>

    </form>
        <div id="sample"></div>
</div>

Here's my Javascript code. In this code, when I trigger the submitted button from html, it will display the info of the user and append a div for each submitted info of the users.

var data = [];
var i, item;

function myForm(event){
    event.preventDefault();
    var name = document.getElementById("name").value;
    var phone = document.getElementById("phone").value;
    var bday = document.getElementById("bday").value;
    var email = document.getElementById("email").value;
    var pWord = document.getElementById("pWord").value;
    var age = document.getElementById("bday").value;
    var ageValue;




    var Bdate = document.getElementById("bday").value;
    var Bday = +new Date(Bdate);
    ageValue = ~~ ((Date.now() - Bday) / (31557600000));
    var theBday = document.getElementById("age");
    theBday.innerHTML = ageValue;


    var userObject = {
        name: name,
        phone: phone,
        bday: bday,
        email: email,
        pWord: pWord,
        ageValue: ageValue,

    };
       data.push(userObject);

        document.getElementById("sample").innerHTML = ""; //Prevents duplicate
        for (var i=0 ; i <data.length ; i++){
            var theDiv ;
            var container ;
            var button;

            theDiv = document.createElement( "div" );
            button = document.createElement( "button");
            button.setAttribute("id", "remove");
            button.remove(sample);
            theDiv.style = "background-color:pink; border-style:solid; margin:1%;";

            for (item in data[i]) {
                var x = item + ":" + data[i][item] + "</br>" ;              

                theDiv.innerHTML += item + ":" + data[i][item] + "</br>" ;

            }
            button.innerHTML += "Remove";   
            button.style = "background-color:maroon; color:white;"; 

            container = document.getElementById( "sample" );
            container.appendChild( theDiv );
            theDiv.appendChild (button);
        }


    console.log(data);

}

I want to to create a button for each appended div. The button will have the function of removing the entire div where the button belong.

Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
Mavis Zero
  • 41
  • 1
  • 10
  • 1
    Avoid [using "for...in" to iterate over an array](https://stackoverflow.com/q/500504/5217142). Don't attempt to assign the same `id` attrribute to more than one element. The ` button.remove(sample);` is pseudo code. Have you tried to implement it? Should the `userObject` entry in the `data[]` array for the button also be removed? – traktor May 18 '18 at 06:13
  • Ok i got it, sorry i'm not familiarize with the pseudo code. The userObject entry in the data[] array should remove if the button was trigger – Mavis Zero May 18 '18 at 06:34

2 Answers2

1

A reasonably simple algorithm to correctly remove objects from the list is to provide a data- attribute value on each remove botton that gives its original index in the data array. (The attribute name used below is data-index).

Then take the inline code that adds objects and turn it into three functions to

  • (re-)draw all objects held in the data array.
  • add a single object to data and redraw all objects.
  • remove an object from the data array (coded as a remove button onclick handler) and redraw all objects.

The code already redraws all object when adding a new object is added, so redrawing everything when removing an object keeps it on the same level of simplicity.


Example code for simplified form:

"use strict";
var data = [];

function myFormData(event){

    // halper functions
    function addData( userObject) {
        data.push(userObject);
        redrawList();
    }
    function removeData( event) {
       var index = this.getAttribute("data-index");
       data.splice( index,1);
       redrawList();
    }
    function redrawList() {
        var container = document.getElementById( "sample" );
        container.innerHTML = ""; // reset list displayed on page
        for (var index=0 ; index <data.length ; index++){
            var theDiv = document.createElement( "div" );
            var divHTML = "";
            var button = document.createElement( "button");
            var userObject = data[index];

            for( var item in userObject) {
                if( !userObject.hasOwnProperty( item)) {
                     continue; // ignore inherited properties
                }
                divHTML +=  item + ":" + userObject[item] + "</br>" ;
            }
            theDiv.innerHTML = divHTML;
            theDiv.style = "background-color:pink; border-style:solid; margin:1%;";
            button.type="button";
            button.setAttribute("data-index", index);
            button.innerHTML = "remove";
            button.style = "background-color:maroon; color:white;";
            button.onclick=removeData;   
            theDiv.appendChild (button);
            container.appendChild( theDiv );
        }
    }

    //  handle form submit event to add an event
    event.preventDefault();
    // cut down form:
    var name = document.getElementById("name").value;
    var userObject = {
        name: name
    };
    addData( userObject);
    // console.log(data);  // not used in code example
}
<div id="format">
  <form id="myForm" onsubmit="myFormData(event);">
    <b>Name:</b></br>
    <input type="text" name="name" id="name"  required="required" ></input></br>
    <button type="submit" name="submit" id="submit" value="Submit"
      onsubmit="myFormData(event)" >Submit</button>
  </form>
  <div id="sample">
  </div>
</div>

Note the code uses getAttribute("data-index") in case target browser support for element.dataset is unknown or absent. Function names myForm and myData were changed to myFormData as I presume they are the same function.

Probable issue: the existing code comment that clearing the sample list prevents duplicates is wrong. In the example code, clicking the submit button multiple times adds the same user. You could add a test to check for duplicate email addresses when adding a user to the list, but such code is outside the scope of this question. You may also wish to consider resetting the form after adding data to the "sample" list.

traktor
  • 17,588
  • 4
  • 32
  • 53
  • the program becomes stable. Thanks. Can i ask another question? I want to use console.log to show the deleted user's details For Example I entered 3 users User 1: John User 2: Matt User 3: Joy then i remove Matt, I want User 2 to display in the console. thanks – Mavis Zero May 21 '18 at 02:51
  • That should be easy - but please try writing some code to do it yourself. Studying the algorithm to the point of understanding it should help determining where to put the code. See "asking" in the [help center](https://stackoverflow.com/help) for more information. – traktor May 21 '18 at 09:53
  • I already did that. hahaha it's so nice to discover codes. I'm a beginner in arrays and loops. Thaanks – Mavis Zero May 21 '18 at 10:32
0

check the fiddler, i have implemented with a single value 'name'.

var data = [];
var i, item;

function myForm(event){
    event.preventDefault();
    var name = document.getElementById("name").value;
   
    var userObject = {
        name: name
        };
       data.push(userObject);

        document.getElementById("sample").innerHTML = ""; //Prevents duplicate
        for (var i=0 ; i <data.length ; i++){
            var theDiv ;
            var container ;
            var button;
            var index;

            theDiv = document.createElement( "div" );
            button = document.createElement( "button");
            index = document.createElement("input");
            index.setAttribute('hidden', 'true');
            button.setAttribute("id", "remove");
            button.setAttribute("onclick", "removeItem(this)");            

            for (item in data[i]) {
             var x = item + ":" + data[i][item] + "</br>" ;              
                theDiv.innerHTML += item + ":" + data[i][item] + "</br>" ;
                index.value += i; 

            }
            button.innerHTML += "Remove";   
           
            container = document.getElementById( "sample" );
            container.appendChild( theDiv );
            theDiv.appendChild (button);
            theDiv.appendChild(index);
        }
}
function removeItem(event){
 let el = event;
    let index = el.parentNode.lastElementChild.value;
    el.parentElement.remove();
    data.splice(index,1);
}
   <div id="format">
         <form id="myForm" onsubmit="myForm(event)">
         <b>Name:</b>
         <input type="text" name="name" id="name"  required="required" >
        
        <button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>

    </form>
        <div id="sample"></div>
</div>
Sangram Nandkhile
  • 17,634
  • 19
  • 82
  • 116
Akhil Aravind
  • 5,741
  • 16
  • 35
  • Ok i get it now. Thank you! :D – Mavis Zero May 18 '18 at 06:27
  • 2
    Not fully debugged. The value in the hidden input is the `data[]` index when the sample was created. This is not constant if you later remove preceding entries in the array. If you "delete" elements starting from the first, and then add another entry, the entries for data entries removed from the sample container, but not the data array, re-appear. – traktor May 18 '18 at 06:29
  • @traktor53 Yes it appears that there is a bug in the program. I tried this, time goes by , some of data that should be deleted re appears and replacing the other data – Mavis Zero May 18 '18 at 07:42
  • @akhilaravind when i console your program, i noticed that there are some issues in the objects in the array, the program only remove the current [0] index in the array whether what div i choose to delete, it only delete specifically in terms of html, but not in the console log. Anyway thank you for the effort, i appreciate it. – Mavis Zero May 18 '18 at 07:56