Muhammad Hassan
Muhammad Hassan

Reputation: 1304

Submit Form Using AJAX `onKeyUp` In Each <tr> Row Of A Table In Vanilla JavaScript

I have a table full of rows that have <form> tag inside them and have <input> tags inside cells as shown in the below markup.

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th> 
  </tr>
  <tr>
   <form>
    <td><input onkeyup="return searchGet(this.parentNode.parentNode)" type="text" name="Firstname"/></td>
    <td><input onkeyup="return searchGet(this.parentNode.parentNode)" type="text" name="Lastname"/></td>
    <td><input onkeyup="return searchGet(this.parentNode.parentNode)" type="number" name="Age"/></td>
   </form>      
  </tr>
  <tr>
   <form>
    <td><input onkeyup="return searchGet(this.parentNode.parentNode)" type="text" name="Firstname"/></td>
    <td><input onkeyup="return searchGet(this.parentNode.parentNode)" type="text" name="Lastname"/></td>
    <td><input onkeyup="return searchGet(this.parentNode.parentNode)" type="number" name="Age"/></td>
   </form>      
  </tr>
........
</table>

Now I want to submit the each row form using pure Vanilla JavaScript Ajax function whenever anyone types in the input tags to their respective form. My Ajax function is simple that is getting the Form Object to pick all form elements value whenever wee type in any element.

function searchGet(incomingForm) {
    var FD = new FormData(incomingForm);    
    var ajx = new XMLHttpRequest();
    ajx.onreadystatechange = function () {
        if (ajx.readyState == 4 && ajx.status == 200) {
            console.log(ajx.responseText);
        }
    };
    ajx.open("POST", "submit.php", true);
    ajx.send(FD);
    return false;
}

Now the problem is that this.parentNode.parentNode is not picking <FORM> element but it's directly picking <TR> element. So how can I make it working perfectly?

Note: I tried many other ways but not able to make it like...

Upvotes: 0

Views: 178

Answers (1)

ariel
ariel

Reputation: 16140

As you can see here, you can't place forms between tr elements. The solution is restyle to resemble a table. Also, use addEventListener to have a more elegant code.

document.body.addEventListener("keyup", function(ev) {
  if (ev.target.tagName == "INPUT") {
    console.log(ev.target.closest("form").id);
  }
});
div { display: inline-block; width: 100px; }
input {width: 95px; }
<div>Firstname</div>
<div>Lastname</div>
<div>Age</div>
<form id="first">
  <div><input type="text" name="Firstname" /></div>
  <div><input type="text" name="Lastname" /></div>
  <div><input type="number" name="Age" /></div>
</form>
<form id="second">
  <div><input type="text" name="Firstname" /></div>
  <div><input type="text" name="Lastname" /></div>
  <div><input type="number" name="Age" /></div>
</form>

Upvotes: 1

Related Questions