skip to Main Content

Currently, I am making a table. In this table, the rows have 2 cells that have input fields that take in first names and last names.

Problem: Right now, all that it does is create on row with inputs in each cell. However, the new row that gets created does not work properly (you do not need to fill out this new row to create another row, it is still picking up the first row).

Question: How can I make a table that creates a new row that have two input cells?

Note: It is important that each input is unique because I need to take the text inputted to create a list.

const table = document.querySelector('#table');
const addRowButton = document.querySelector('#addRow');

//let names = []; I'm not sure if I should use an array or a class to store the names
let rowNumber = 0; //Maybe I can use a for loop using "i"? I couldn't get that to work, though

function addRow() {
    const row = table.insertRow(-1);
    const cell1 = row.insertCell(0);
    const cell2 = row.insertCell(1);
    const firstNameInput = document.createElement("input");
    const lastNameInput = document.createElement("input");

    firstNameInput.type = "text";
    cell1.appendChild(firstNameInput);
        
    lastNameInput.type = "text";
    cell2.appendChild(lastNameInput);

    //When a first and last name is entered, a new row is added
    //When this happens, the inputs should be able to pass their own values
    table.addEventListener('change', () => {
        if (firstNameInput == null || lastNameInput == null) {
            return null;
        } else if (firstNameInput.value && lastNameInput.value) {
            rowNumber++;
            addRow();
            let firstName = firstNameInput.value;
            let lastName = lastNameInput.value;
        }
    })   
}

addRowButton.addEventListener('click', addRow);
#input-article.hidden {
    display: none;
}

table {
    text-align: center;
    align-items: center;
}

th {
    width: 50vmin;
    height: 10vmin;
    font-size: 20pt;
    font-weight: 800;
}

input {
    width: 50vmin;
    height: 5vmin;
    text-align: center;
    align-items: center;
    font-size: 18pt;
    font-weight: 400;
    font-family: Georgia, 'Times New Roman', Times, serif;
    border: 0;
    padding: 0;
}

#submit {
    background-color: blue;
    color: white;
    border: 0;
    position: absolute;
    left: 95vmin;
}

#output-article.hidden {
    display: none;
}
<!DOCTYPE html>
<html lang="en">

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE-edge">
        <meta name="viewport", content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Christian Davis">
        <link rel="stylesheet" href="styles.css">
        <title>Random Group Generator</title>
    </head>

    <body>
        <article id="input-article">
            <table id="table" border="1">
                <tr>
                    <th>First Name:</th>
                    <th>Last Name:</th>
                </tr>
            </table> <br>

            <button id="addRow">Add Row</button>
            <button id="submit">Submit</button>
        </article>

        <script src="app.js"></script>
    </body>
</html>

2

Answers


  1. Look, I will modify your hole code starting with the function addRow, try this :

    function addRow(){
    // I prefer using the let because it don't take from the computer memory after finishing using it
    
    // I use the document.createElement oftenly
    let row = document.createElement("tr")
    let c1 = document.createElement("td") // = cell1
    let c2 = document.createElement("td") // = cell2
    let fnInput = document.createElement("input") // = firstNameInput
    let lnInput = document.createElement("input") // = lastNameInput
    
    rowNumber++
    fnInput.setAttribute("id", `fn${rowNumber}`) //We set the desired ID as it is unique, you said that above
    lnInput.setAttribute("id",`ln${rowNumber}`)
    
    //The inputs are text type in default
    row.appendChild(c1)
    row.appendChild(c2)
    table.appendChild(row)
    check(rowNumber) //Look down to find the function !
    }
    
    // This small function would solve your problem . it is called in the addRow function !
    
    function check(i) {
    
    document.getElementById(`fn${i}`).addEventListener("change", function(){
    let element = document.getElementById(`fn${i}`), element2 = document.getElementById(`ln${i}`)
    // Checking the existance of another row after this, if yes, do nothing
    if(i != rowNumber-1) {}
    // If there is no another row after, execute the following :
    else {
    // Checking if the both inputs have values, if yes, then we can add a row
    if(element.value != null && element.value != "" && element2.value != null && element2.value != "") addRow()
    // Else, don't add
    else {}
    }
    })
    
    document.getElementById(`ln${i}`).onchange = document.getElementById(`fn${i}`).onchange
    }
    

    this code is written and still not tested, please test it (as I wrote it from mobile without a compiler in it) and tell me the results, hope this helps

    Login or Signup to reply.
  2. pls try this. for each input added you have a new created id achieved using setAttribute. then to control adding row I used removeEventlistener togetther with addEventListener. I also used arrays to store your inputs, you can then retrieve needed data easily. You could also have added same class and used forEach with querySelectorAll

    const table = document.querySelector('#table');
    const addRowButton = document.querySelector('#addRow');
    let counter = 0
    let cellOneId,cellTwoId
    //let names = []; I'm not sure if I should use an array or a class to store the names
    let rowNumber = 0; //Maybe I can use a for loop using "i"? I couldn't get that to work, though
    let arrayFirstName = []
    let arrayLastName = []
    let lastNameValue
    let firstNamevalue
    
    function addRow(counter) {
        
        row = table.insertRow(-1);
        let cellOne = row.insertCell(0);
        cellOneId="cellOneId" + counter
        cellOne.setAttribute("id",cellOneId)
        let cellTwo = row.insertCell(1);
        cellTwoId="cellTwoId" + counter
        cellTwo.setAttribute("id",cellTwoId)
    }
    
    
    function addRowInput() {
        lastNameValue = ""
        firstNamevalue = ""
        addRowButton.removeEventListener('click',addRowInput)
        counter+=1
        addRow(counter)
        let cellone = document.getElementById(cellOneId)
        let celltwo = document.getElementById(cellTwoId)
        const firstNameInput = document.createElement("input");
        let firstname = "firstname"+counter
        firstNameInput.setAttribute("id",firstname)
        firstNameInput.setAttribute("required",'')
        const lastNameInput = document.createElement("input");
        let lastname = "lastname"+counter
        lastNameInput.setAttribute("id",lastname)
        lastNameInput.setAttribute("required",'')
    
    
        firstNameInput.type = "text";
        cellone.appendChild(firstNameInput);
        //let inputFirstName = document.getElementById(firstname)
            
        lastNameInput.type = "text";
        celltwo.appendChild(lastNameInput);
        //let inputLastName = document.getElementById(lastname)
    
    
        lastNameInput.addEventListener('change',()=>{
            lastNameValue = lastNameInput.value
            arrayLastName.push(lastNameValue) 
            if(lastNameValue!="" && firstNamevalue!=""){
                addRowButton.addEventListener('click',addRowInput)
                lastNameValue=""
                firstNamevalue=""
            }
        })
    
    
        firstNameInput.addEventListener('change',()=>{
            firstNamevalue = firstNameInput.value
            arrayFirstName.push(firstNamevalue)
            if(lastNameValue!="" && firstNamevalue!=""){
                addRowButton.addEventListener('click',addRowInput)
                firstNamevalue=""
                lastNameValue=""
            }
                
        })
         
    
    }
    
    
    addRowInput()
    #input-article.hidden {
        display: none;
    }
    
    table {
        text-align: center;
        align-items: center;
    }
    
    th {
        width: 50vmin;
        height: 10vmin;
        font-size: 20pt;
        font-weight: 800;
    }
    
    input {
        width: 50vmin;
        height: 5vmin;
        text-align: center;
        align-items: center;
        font-size: 18pt;
        font-weight: 400;
        font-family: Georgia, 'Times New Roman', Times, serif;
        border: 0;
        padding: 0;
    }
    
    #submit {
        background-color: blue;
        color: white;
        border: 0;
        position: absolute;
        left: 95vmin;
    }
    
    #output-article.hidden {
        display: none;
    }
        <body>
            <article id="input-article">
                <table id="table" border="1">
                    <tr>
                        <th>First Name:</th>
                        <th>Last Name:</th>
                    </tr>
                </table> <br>
    
                <button id="addRow">Add Row</button>
                <button id="submit">Submit</button>
            </article>
    
            <script src="app.js"></script>
        </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search