Home > other >  show / hide columns based on value in Javascript
show / hide columns based on value in Javascript

Time:10-28

I'm still very inexperienced in javascript, nevertheless I'd like to try my hand at it and would be very happy to get some support. I have the following scenario:

I have a table, with several rows and 3 columns. Column 1 would be a name, column 2 would be a number (ID), column 3 would be a value.

I have a value (ID) in a WebApp that I would like to search for in the table in column 2 and would like to display only that row. What is the best way to start? What exact topics should I look at more closely to implement this? I would be very happy to receive an answer!

<div id="datatable" align="center">
    <table>
        <tr id="class1">
            <td>Person 1</td>
            <td>1234561</td>
            <td>800</td>
        </tr>
         <tr id="class1">
            <td>Person 2</td>
            <td>1234562</td>
            <td>1800</td>
        </tr>
         <tr id="class1">
            <td>Person 3</td>
            <td>1234563</td>
            <td>1400</td>
        </tr>
    </table>
</div>

I have already searched online for similar scripts, however this doesn't seem to be needed that often! So I would like to tackle this myself now. But how to start?

CodePudding user response:

You can select the table and loop through its rows with forEach and check if the row.cells[1] ( which is the ID cell ), its textContent start with input value, If not hide it with display: none and if it match show it with display: table-row

const personTable = document.querySelector('table');
const tableRows = [...personTable.rows];
const input = document.querySelector('input');

input.addEventListener('input', (e) => {
  const value = e.target.value;
  const rows = tableRows.forEach(row => {
    const match = row.cells[1].textContent.trim().startsWith(value.trim())
    if (match) {
      row.style.display = 'table-row'
    } else {
      row.style.display = 'none'
    }
    
  })
})
<div id="datatable" align="center">
    <table id="person-table">
        <tr id="class1">
            <td>Person 1</td>
            <td>1234561</td>
            <td>800</td>
        </tr>
         <tr id="class1">
            <td>Person 2</td>
            <td>1234562</td>
            <td>1800</td>
        </tr>
         <tr id="class1">
            <td>Person 3</td>
            <td>1234563</td>
            <td>1400</td>
        </tr>
    </table>
</div>

<input type="text" />

CodePudding user response:

First of all, you should research DOM manipulation, so that you can actually access and manipulate the values necessary. Also, you should research how to work with classes. A knowledge of loops is also needed. Finally, some understanding of HTML & CSS is necessary. All of this material is available on W3schools, so check there.

EDIT: You didn't ask for the coded solution, which is why I'm not giving it.

CodePudding user response:

There are so many skills required it's quite hard to work out which without making it.

One thing that I have changed is your data from html into an array. I find arrays can be much easier to work with once you get your head around them — and how you can output them to HTML.

There are many ways to do this — that is important to know. There isn't really such thing as a "right" answer here.

// Arrays https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
const people = [
  { name: "Person 1", num: 1234, details: 800 },
  { name: "Person 2", num: 3456, details: 1800 },
  { name: "Person 3", num: 5678, details: 1400 }
];

// Query selectors — https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
const tbody = document.querySelector("#tbody");
const searchBox = document.querySelector("#search-box");

// * Get the matching items
// Functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
const selectList = () => {
  // * If nothing has been typed...
  // Input value https://www.w3schools.com/jsref/prop_text_value.asp
  // if statements https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
  if(searchBox.value == ""){
    return people;
  }
  // Array filtering — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
  return people.filter(person => {
    // Converting numbers to strings — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
    // String includes — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
    return (person.num.toString()).includes(searchBox.value)
  })
}

// * Convert the array into data for the table
const getData = (found) => {
  // * If the result of our filter has no values
  if(found.length == 0){
    return `<tr>
      <td colspan="3">No results found</td>
    </tr>`
  }
  // Otherwise, create the rows
  // Template literals — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
  return found.map(person => `<tr id="class1">
            <td>${person.name}</td>
            <td>${person.num}</td>
            <td>${person.details}</td>
        </tr>`).join("\n");
}

// Called whenever the textbox changes
const render = () => {
  
  // Get the list
  const found = selectList();
  // Convert to html
  const data = getData(found);
  
  // Empty the body
  tbody.textContent = "";
  
  // Append the new data
  tbody.innerHTML = data;
}

// Event listeners — https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
searchBox.addEventListener('input', render);
render();
<div>
  <input type="text" id="search-box" />
</div>

<div>
  <div id="datatable" align="center">
    <thead>
      <tr>
        <th>Name</th>
        <th>Num</th>
        <th>Details</th>
      </tr>
    </thead>
      <table>
        <tbody id="tbody"></tbody>
      </table>
  </div>
  
</div>

  • Related