Pobieranie danych z tabeli do klasy

0

Hej,

stworzyłem tabelę, do której można dodawać kolejne wiersze i wpisywać w nie dane produktów.
Chciałbym, żeby po dodaniu wiersza, tworzyła się również klasa, do której zostaną wysłane jako parametry te wpisane w dany wiersz - a które potem będę musiał zapisać w LocalStorage (ta część jeszcze niegotowa, bo utkwiłem po stworzeniu samej tabeli :p).

Czy da się to dorobić do tego, co jest, czy potrzebuję jakiegoś nowego, osobnego przycisku (coś w stylu ,,stwórz" gdy wszystkie dane już będą wpisane [bo nie stworzy się (chyba) klasy z pustego wiersza])?
Jak to zrobić dalej, mógłbym prosić o podpowiedzi?
(Próby stworzenia klasy wrzuciłem w komentarze).

<!DOCTYPE html>
<html lang="pl">
    <head>
    <meta charset="UTF-8">
    <title>tabela_produktów</title>
    <style>
        table { width: 70%; }
        table, th, td { border: solid 1px #DDD;
            border-collapse: collapse; padding: 2px 3px; text-align: center;
        }
    </style>
    </head>
    <body onload="startTable()">
        <p>
            <input type="button" id="addRow" value="Dodaj Wiersz" onclick="addRow()"/>
        </p>
        <div id="container"></div>
        <p><input type="button" id="submitButton" value="Zapisz" onclick="submit()"/> </p>
        <script>
            var arrayHead = new Array();
            arrayHead = ["", "Nazwa", "Kategoria(ID)", "Wartość", "Ilość na stanie", "Opis(opcjonalnie)"];

            function startTable(){
                var myTable = document.createElement('table');
                myTable.setAttribute('id', 'myTable');
                var tr = myTable.insertRow(-1);

                for (i=0; i< arrayHead.length; i++){
                    let th = document.createElement('th');
                    th.innerHTML = arrayHead[i];
                    tr.appendChild(th);
                }
                var div = document.getElementById('container');
                div.appendChild(myTable);
            }

            function addRow(){
                var myTab = document.getElementById('myTable');
                var rowAm = myTab.rows.length;
                var tr = myTab.insertRow(rowAm);
                tr = myTab.insertRow(rowAm);

                for(a=0; a<arrayHead.length; a++){
                    let td = document.createElement('td');
                    td = tr.insertCell(a);

                    if(a==0){
                        var button = document.createElement('input');
                        button.setAttribute('type', 'button');
                        button.setAttribute('value', 'Usuń');

                        button.setAttribute('onclick', 'removeRow(this)');

                        td.appendChild(button);
                    }
                    else{
                        var element = document.createElement('input');
                        element.setAttribute('type', 'text');
                        element.setAttribute('value', '');

                        td.appendChild(element);
                    }
                }
               
                //prodClass(name, ID, prValue, amount, descript);
                }

                function removeRow(oButton){
                    var myTab = document.getElementById('myTable');
                    myTab.deleteRow(oButton.parentNode.parentNode.rowIndex);
                }

                function submit(){
                    var tab = document.getElementById('myTable');
                    var arrValues = new Array();

                    for (row=1; row<tab.rows.length -1; row++){

                        for(m=0; m<tab.rows[row].cells.length;m++){
                            var ele = tab.rows.item(row).cells[m];

                            if(ele.childNodes[0].getAttribute('type')=='text'){
                                arrValues.push("'" + ele.childNodes[0].value + "'");
                            }
                        }
                    }
                    console.log(arrValues);
                }


               /* class Product {

                    constructor (name, ID, prValue, amount, descript){
                        this.name = name;
                        this.ID = ID;
                        this.prValue = prValue;
                        this.amount = amount;
                        this.descript = descript;
                    }
                }

                function prodClass (){
                const name = document.getElementById("myTable").rows[1].getElementsByTagName('td');
                const ID = document.getElementById("myTable").rows[2].getElementsByTagName('td');
                const prValue = document.getElementById("myTable").rows[3].getElementsByTagName('td');
                const amount = document.getElementById("myTable").rows[4].getElementsByTagName('td');
                const descript = document.getElementById("myTable").rows[5].getElementsByTagName('td');
                    const prodInstance = new Product(name, ID, prValue, amount, descript);
                productArray.push(prodInstance);
                }*/
            
            </script>
    </body>
</html>
1

@TotalNewbie: Jest wiele sposobów na rozwiązanie tego problemu. Możesz wykorzystać np tablice wierowymiarowe, a potem w momencie zapisu tworzyć obiekty po tej tablicy.
Przykładowy kod funkcji submit mogłby wyglądać tak:


function submit(){
  const tab = [...document.querySelectorAll('#myTable .rows')];

  const data = tab.map((tr,i)=>{	
    const column = [...tr.querySelectorAll('.column')];
    return column.map((td,j)=>{
      const input = td.querySelector('input');
      return input.value;
    })
  })

  const products = data.map((arg)=>{
    return new Product(...arg)
  })

  console.log(products);
}

a tutaj cały działający kod: https://jsfiddle.net/9t4dy5cj/

0

Hej, wrzucam ogarnięty (chyba) do końca - z ponownym pobraniem i wyświetleniem wcześniej zapisanych danych - kod.
Może komuś się kiedyś przyda. :)
Prosiłbym tylko jeszcze jakąś bardziej ogarniętą osobę, żeby sprawdziła, czy wszystko jest ok - u mnie działa, ale wiadomo jak to czasem jest :p.

<!DOCTYPE html>
<html lang="pl">
    <head>
    <meta charset="UTF-8">
    <title>tabela_produktów</title>
    <style>
        table { width: 70%; }
        table, th, td { border: solid 1px #DDD;
            border-collapse: collapse; padding: 2px 3px; text-align: center;
        }
    </style>
    </head>
    <body>
        <p>
            <input type="button" id="addRow" value="Dodaj Wiersz" onclick="addRow()"/>
        </p>
        <div id="container"></div>
        <p><input type="button" id="submitButton" value="Zapisz" onclick="submit()"/> </p>
        <script>
          

class Product {

constructor (name, ID, prValue, amount, descript){
    this.name = name;
    this.ID = ID;
    this.prValue = prValue;
    this.amount = amount;
    this.descript = descript;
}
}

            var arrayHead = new Array();
            arrayHead = ["", "Nazwa", "Kategoria(ID)", "Wartość", "Ilość na stanie", "Opis(opcjonalnie)"];

            function startTable(){
                var myTable = document.createElement('table');
                myTable.setAttribute('id', 'myTable');
                var tr = myTable.insertRow(-1);

                for (i=0; i< arrayHead.length; i++){
                    let th = document.createElement('th');
                    th.innerHTML = arrayHead[i];
                    tr.appendChild(th);
                }
                var div = document.getElementById('container');
                div.appendChild(myTable);
            }

            function addRow(prevProduct){


                var myTab = document.getElementById('myTable');
                var rowAm = myTab.rows.length;
                var tr = myTab.insertRow(rowAm);
                tr.classList.add('rows');
              

                for(a=0; a<arrayHead.length; a++){
                    let td = document.createElement('td');
                   

                    td = tr.insertCell(a);
                    td.classList.add('column');

                    if(a==0){
                        var button = document.createElement('input');
                        button.setAttribute('type', 'button');
                        button.setAttribute('value', 'Usuń');

                        button.setAttribute('onclick', 'removeRow(this)');
                        td.classList.remove('column');
                        td.classList.add('delete');
                        td.appendChild(button);
                    }
                    else{
                        var element = document.createElement('input');
                        element.setAttribute('type', 'text');

                        if (prevProduct && a===1) {
                           element.setAttribute('value', prevProduct.name); } 

                           else if(prevProduct && a===2)
                           {element.setAttribute('value', prevProduct.ID);}

                           else if(prevProduct && a===3)
                           {element.setAttribute('value', prevProduct.prValue);}

                           else if(prevProduct && a===4)
                           {element.setAttribute('value', prevProduct.amount);}

                           else if(prevProduct && a===5)
                           {element.setAttribute('value', prevProduct.descript);}
                          
                        else{
                            element.setAttribute('value', '');
                        }
                        

                        td.appendChild(element);
                    }
                }
               
              
                }

                function removeRow(oButton){
                    var myTab = document.getElementById('myTable');
                    myTab.deleteRow(oButton.parentNode.parentNode.rowIndex);
                }

                function submit(){
                    const tab = [...document.querySelectorAll('#myTable .rows')];
                    const data = tab.map((tr,i) =>{
                        const column = [...tr.querySelectorAll('.column')];
                        return column.map((td,j) =>{
                            const input = td.querySelector('input');
                            return input.value;
                        })
                    })

                    const products = data.map((arg) =>{
                        return new Product(...arg)
                    })
                    console.log(products);
                    localStorage.setItem('saved', JSON.stringify(products));
                }


                function restoreTable(){
                    var prevTableData = JSON.parse(localStorage.getItem('saved'));
                    console.log(prevTableData);

                    const prevProducts = prevTableData.map((arg) =>{
                        console.log(arg);
                        return new Product(arg.name, arg.ID, arg.prValue, arg.amount, arg.descript);
                    })
                        prevProducts.forEach(element => {
                            addRow(element);
                        });

                    
                    console.log(prevProducts);
                }

                startTable();
                restoreTable();

            </script>
    </body>
</html>
1

Powtóka ze słówek, bo są ważne:

"Klasa" to nie "Obiekt"

1 użytkowników online, w tym zalogowanych: 0, gości: 1