Search code examples
javascriptfunctionfor-loopalert

How to output the alert into rows per click instead of per variable


1

function getCheckbox() {
var checks = document.getElementsByClassName('checks');
  var id_value = '';
  var title_value = '';
  var type_value = '';
  var date_value = '';
  var url_value = '';
for (i = 0; i < checks.length; i++) {
  if (checks[i].checked === true) {
  var row = checks[i].closest('tr');
  id_value += checks[i].value + " ";
  title_value += row.querySelector('.checks-title').textContent + " ";
  type_value += row.querySelector('.checks-type h6').textContent + " ";
  date_value += row.querySelector('.checks-date').textContent + " ";
  url_value += row.querySelector('.checks-url a').getAttribute('href') + " ";
        }
    }

var check_result = "ID: " + id_value + "\nTitle: " + title_value + "\nType: " + type_value + "\nDate: " + date_value + "\nURL: " + url_value;
alert (check_result);
}

(the example shows that I have three rows selected)

what I am trying to achieve is something like:

  • ID, Title, Type, Date, URL

  • ID, Title, Type, Date, URL

  • ID, Title, Type, Date, URL

Instead I currently have: (refer to screenshot)

  • ID, ID, ID

  • Title, Title, Title

  • Type, Type, Type

  • Date, Date, Date

  • URL, URL, URL

what should I change in my var check_result to get what I need?


Solution

  • Rather than adding each check into a variable by type, create an array that will hold each row as a string (rows). Then, append each column of the row into a temporary string (str), and then push that string as a new element of the rows array.

    Then, to print your rows, first, create a header row, then use .join('\n') on your array to join each element (which are the row strings) by newlines, thus putting each row an a new line.

    Just like this:

    function getCheckbox() {
      var checks = document.getElementsByClassName('checks');
      var rows = [];
      for (i = 0; i < checks.length; i++) {
        if (checks[i].checked === true) {
          var str = "";
          var row = checks[i].closest('tr');
          str += checks[i].value + " ";
          str += row.querySelector('.checks-title').textContent + " ";
          str += row.querySelector('.checks-type h6').textContent + " ";
          str += row.querySelector('.checks-date').textContent + " ";
          str += row.querySelector('.checks-url a').getAttribute('href') + " ";
          rows.push(str);
        }
      }
    
      var header = "ID, Title, Type, Date, URL\n";
      alert(header + rows.join('\n'));
    }