0

my html code is like that:

<table>
<input type="text" name="FirstInput">
....
<input type="text" name="LastInput">
</table>

my question is that, how could I traverse all the input? In fact what I want is to verify whether all the input are empty, I think if I can just traverse all the input then it is possible to do that. But how could I traverse all the value of input inside a table? Thank you very much

5
  • 1
    for (const elem in document.querySelectorAll('table input')) { console.log (elem); ... } Commented Mar 12, 2018 at 15:22
  • thank you naomik, but could you please explain more in detail? thank you Commented Mar 12, 2018 at 15:25
  • what is "table input", do you mean i should add an id for the table? thank you Commented Mar 12, 2018 at 15:26
  • Read documentation of querySelectorAll(): link Commented Mar 12, 2018 at 15:49
  • Table input is a DOM query selector. It means any input in any table (its css like syntax) Commented Mar 12, 2018 at 16:00

1 Answer 1

1

Try this one. If you want to put input under table, you should do it correctly.

<table>
  <input>
  <input>
</table>

That code will be parsed by the browser like this.

<input>
<input>
<table>
</table>

document.getElementById('form').addEventListener('submit', e => {
  e.preventDefault();
  
  const columns = document.querySelectorAll('#form table tbody tr td input');
  const inputs = Array.from(columns)
    .filter(elm => elm.name !== '')
    .reduce((acc, cur) => ({ ...acc, [cur.name]: cur.value }), {});
    
  console.log(inputs);
    
  return false;
});
<form id="form">
  <!-- ... -->
  <table>
    <tbody>
      <tr>
        <td><input name="fullname" placeholder="fullname" type="text"></td>
      </tr>
      <tr>
        <td><input name="username" placeholder="username" type="text"></td>
      </tr>
      <tr>
        <td><input name="email" placeholder="email" type="email"></td>
      </tr>
      <tr>
        <td><input type="submit"></td>
      </tr>
    </tbody>
  </table>
  <!-- ... -->
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much. but the problem is i dont want to read allelements in one form. i want only parts of input inside a table. thank you very much
@martinwang1985 Edited. We need to use table element correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.