Добавление новой строки в таблицу с тремя столбцами Javascript html функция щелчка - PullRequest
0 голосов
/ 02 марта 2020

Описание

Я бы хотел добавить строку, используя javascript с тремя столбцами к таблице в html. Я создаю таблицу, в которой пользователь может ввести свой собственный текст и добавить текст вместе с двумя другими частями информации в таблицу в три столбца. Текущий код, который у меня есть, не будет отображать новую строку. Код также включает в себя функцию перетаскивания, с помощью которой пользователь может щелкнуть строку и перетащить ее в другую позицию в таблице. Я спрашиваю совета относительно того, почему, когда я нажимаю кнопку щелчка, это не добавляет новую строку в таблицу. edit: код теперь работает после обновления, но оператор else ничего не делает.

Javascript

 function addRow(mytable) {
 var food = document.createTextNode(document.querySelector('.input').value);
 var category = document.createTextNode(document.querySelector('.input2').value);
 var time = document.createTextNode(document.querySelector('.input3').value);
 document.querySelector('.input').value = '';
  document.querySelector('.input2').value = '';
   document.querySelector('.input3').value = '';
  // Get a reference to the table
  if (food !== '') {
  var tableRef = document.getElementById(mytable);
  var attr = document.createAttribute('draggable');
  attr.value = 'true';
  // Insert a row at the end of the table
  var newRow = tableRef.insertRow(-1);
  newRow.setAttributeNode(attr);
  newRow.className = 'draggable';

  // Insert a cell in the row at index 0
  var newCell = newRow.insertCell(0);
  var newCell2 = newRow.insertCell(1);
  var newCell3 = newRow.insertCell(2);

   var newText = food;
   var newText2 = category;
   var newText3 = time;

  newCell.appendChild(newText);
  newCell2.appendChild(newText2);
  newCell3.appendChild(newText3);
  addEventsDragAndDrop(newRow);
   }
   //not working for some reason
   else {
     document.getElementById("msg").innerHTML = "Please enter a name";
   }
}

javascript click

 document.getElementById('btn').addEventListener('click', function( {addRow('mytable');});

HTML

<table id="mytable">
                   <tr>
                     <th>Component</th>
                     <th>Category</th>
                     <th>Time</th>
                   </tr>

                   <div id="addRow"></div>

                </table>

1 Ответ

0 голосов
/ 02 марта 2020

Несколько настроек ниже, но требуется больше деталей, только один ввод текста для компонента, но можно добавить больше для приготовления / времени

function addRow(mytable) {
             var newItem = document.createTextNode(document.querySelector('.input').value);
             var category = document.createTextNode("Cook");
             var time = document.createTextNode("time");
             document.querySelector('.input').value = '';
          // Get a reference to the table
           if (newItem != '') {
              var tableRef = document.getElementById(mytable);
              var attr = document.createAttribute('draggable');
              attr.value = 'true';
          // Insert a row at the end of the table
              var newRow = tableRef.insertRow(-1);
              newRow.setAttributeNode(attr);
              newRow.className = 'draggable';

          // Insert a cell in the row at index 0
              var newCell = newRow.insertCell(0);
              var newCell2 = newRow.insertCell(1);
              var newCell3 = newRow.insertCell(2);

              var newText =  newItem;
              var newText2 =  category;
              var newText3 = time;

              newCell.appendChild(newText);
              newCell2.appendChild(newText2);
              newCell3.appendChild(newText3);
              addEventsDragAndDrop(newRow);
           }
        }
        
        document.getElementById('btn').addEventListener('click', function(){addRow('mytable');});
<table id="mytable">
                   <tr>
                     <th>Component</th>
                     <th>Category</th>
                     <th>Time</th>
                   </tr>
                   <tr class="draggable" id="draggable" draggable="true">
                   <td>Food goes here</td>
                   <td>Cook</td>
                   <td>10</td>
                 </tr>

                   <div id="addRow"></div>

                </table>
                
                
                                <label for='component'>component</label>
                <input class='input' id='component' />
                <button id='btn'>add component</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...