Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to check if a text inside a <td> elemet is already in the table?

Hi. I want to add a feature to a project of mine.

In my project i have 3 inputs: first input is for the the user name. second input is for the name of the tool and third input is for the number of the tool.

I want to check if a user already entered a specific tool number inside my table to indicate to him that the specified tool has already been taken.

I have a table that contains a row. I want to select the second cell (td) from each table row which represent the toolNumber and loop through each of the table row and check if the text inside the <td> element is the same text that the user has been applied in the third input!

this is what i tried to do:

    static checkIfExists(numValueInput) {
    const activeList = document.querySelectorAll("#tool-list tr");
    console.log(activeList);
    for(let i = 0;  i < activeList.length; i++) {
      const td = activeList[i].getElementsByTagName("TD")[2];
        if(td.innerHTML === numValueInput) {
          console.log("the tool is already taken");
        }
    }
  }  

I Make the call to this fucntion in line 247, toolNameInput is the variable that holds the value of the third input from the user.

  UI.checkIfExists(toolNameInput);

current snapshot: http://w.trhou.se/v09rkvbdnt

i get this error:

mainapp.js:83 Uncaught TypeError: activeList[i].getElementsByName is not a function
    at Function.checkIfExists (mainapp.js:83)
    at HTMLFormElement.<anonymous> (mainapp.js:247)

I don't know why its not working ill appreciate any help.

Steven Parker

8 Answers

static checkIfExists(numValueInput) {
    const tbl = document.querySelectorAll("#tool-list"); //put id of the table
    console.log(tbl);

  //using ES6 here with 'map'
   tbl.rows.map(row => 
     const cells = row.getElementByTagName('td');

     cells.map(cell =>
        if (cell.innerHTML === numValueInput){
            console.log('the tool is already taken');
        }

     );
  )

  }  

this worked for u?, can u say what’s wrong with my code? i’m not at home rn

Im curently in the computer and im getting this erro when i try to implement ur solution:

Uncaught SyntaxError: Unexpected strict mode reserved word

current snapshot: http://w.trhou.se/jmxzrubv3a

    static checkIfExists(numValueInput) {
//i get ref to all the tr in the table
    const activeList = document.querySelectorAll("#tool-list tr");
    console.log(activeList);
i loop through each tr
    for(let i = 0;  i < activeList.length; i++) {
//i want to get in each tr the <td> in index 2 which reprsent the number
      const td = activeList[i].getElementsByTagName("TD")[2];
//then i check if the content in the td is the same as in the third input value
        if(td.innerHTML === numValueInput) {
          console.log("the tool is already taken");
        }
    }
  }  

the logic seems to be ok to me where im wrong?

Steven Parker
Steven Parker
229,732 Points

You're close but:

  • is this a class method? if not, you should have "function" instead of "static"
  • the index for the second data item should be 1 instead of 2
    • —OR— you could select it using: querySelector("td:nth-child(2)")
  • "innerHTML" is a string, so to compare it to a number argument:
    • use a normal equality (==) instead of a type-sensitive one (===)
    • —OR— convert the innerHTML to a number
    • —OR— convert the argument into a string

Hi steven! This is a class method in the UI class so i use static for it. the index for the seocnd data item is 2 because it's in the second index as u can see here

   <td>${tool.name}</td>
            <td>${tool.toolName}</td>
            <td>${tool.number}</td>
            <td><button class= "btn btn-danger btn-sm delete">מחק כלי</button></td>
            <td>${tool.date}</td>
            `;

it's tool.number which is the third element which mean it's in the second index.

***SEE THE MESSAGE BELOW **

Hi steven look at this :

 static checkIfExists(numValueInput) {
    let isTrue = false;
      ///i select all the tr nodes in the table.
    const activeList = document.querySelectorAll("#tool-list tr");
    console.log(activeList);
     //i loop through the array of tr elements
    for(let i = 0;  i < activeList.length; i++) {
      //im getting access in each row to the "td" element that is in index 2 in the array which reprsent the tool number in the table.
      if(activeList.innerHTML !== "") {
        const td = activeList[i].getElementsByTagName("TD")[2];
        console.log(td);
        if(td.innerHTML == numValueInput) {
          isTrue  = true;
        } else {
          isTrue = false;
        }
      }
    }

      return isTrue;
  }  

I make the call to this function in the Add a tool event listener here, i copy part of the code:

   //first i check if the function return true
    } else if(UI.checkIfExists(numberInput) === true) {
   //if so i give an alert
           UI.showAlert("tool is in use","success",3000);
           UI.clearInputFields();
///and then stop the execution of the function
           return;
    } else {
        const tool = new Tool(nameInput, toolNameInput, numberInput, new Date().toLocaleString());
          //Add tool to UI. we pass into the func the tool var which hold a Tool object and in this func in the row we assign the value of the inputs to each tool property
          UI.addToolToList(tool);



        //Add the tool to the localStorage
          Store.addTool(tool);

        //show success message
          UI.showAlert(` ${toolNameInput} ${numberInput} התווסף בהצלחה לרשימת הכלים, אנא השאר חוגר בשולחן האחמ"ש`, "success",4500);

        //clear each input field after we submit an entry
          UI.clearInputFields();
      }
});

I TRIED THIS AS WELL, SAMR RESULT:

 } else {
          const tool = new Tool(nameInput, toolNameInput, numberInput, new Date().toLocaleString());
          const inside = UI.checkIfExists(numberInput);
          if(inside === true) {
            UI.showAlert("tool is in use","success",3000);
            UI.clearInputFields();
            return;

          } else {

          //Add tool to UI. we pass into the func the tool var which hold a Tool object and in this func in the row we assign the value of the inputs to each tool property
              UI.addToolToList(tool);


        //Add the tool to the localStorage
              Store.addTool(tool);

        //show success message
              UI.showAlert(` ${toolNameInput} ${numberInput} התווסף בהצלחה לרשימת הכלים, אנא השאר חוגר בשולחן האחמ"ש`, "success",4500);

        //clear each input field after we submit an entry
              UI.clearInputFields();
          }
      }
});

this is 75% working, If i had a tool let's say tool number 7 and then i attempt to add the same tool number it blocks me from doing so. BUT if let's say after i add tool number 7 i add another tool and then i try to add tool number 7 it passes the check!

look: https://gyazo.com/c56bd1c14a8316557bdfea223745bb96

this is the current snapshot: http://w.trhou.se/gdtdvesmm4

like i said the logic seemed to be ok and it actually working but if i add another row after it with different tool number and then try to add a tool number that is already in the table it passes the check and this tool get added.

Steven Parker

*****UPDATE** I deleted the else block in the checkIfExists function and it's now works as intended!

    static checkIfExists(numValueInput) {
    let isTrue = false;
      ///i select all the tr nodes in the table.
    const activeList = document.querySelectorAll("#tool-list tr");
    console.log(activeList);
     //i loop through the array of tr elements
    for(let i = 0;  i < activeList.length; i++) {
      //im getting access in each row to the "td" element that is in index 2 in the array which reprsent the tool number in the table.
        const td = activeList[i].querySelectorAll("td")[2];
        console.log(td);
        if(td.innerHTML == numValueInput) {
          isTrue  = true;

        }
    }

    return isTrue;
  }  

i dont need the else block because i set the default value of isTrue to false and later in here i check if the the function is returning true. if the funtion returns true i alert the user that the tool is in use and stop the execution of the code, if it's not true which means false then i added the tool as always.

} else if(UI.checkIfExists(numberInput) === true) {
   //if so i give an alert
           UI.showAlert("tool is in use","success",3000);
           UI.clearInputFields();
///and then stop the execution of the function
           return;
    } else {
        const tool = new Tool(nameInput, toolNameInput, numberInput, new Date().toLocaleString());
          //Add tool to UI. we pass into the func the tool var which hold a Tool object and in this func in the row we assign the value of the inputs to each tool property
          UI.addToolToList(tool);



        //Add the tool to the localStorage
          Store.addTool(tool);

        //show success message
          UI.showAlert(` ${toolNameInput} ${numberInput} התווסף בהצלחה לרשימת הכלים, אנא השאר חוגר בשולחן האחמ"ש`, "success",4500);

        //clear each input field after we submit an entry
          UI.clearInputFields();
      }
});

am i right about this?

Steven Parker
Steven Parker
229,732 Points

:bulb: You also don't need an "else" after a series of conditional blocks that all end with "return".