-1

When I press the submit button I need to find out the form id and pass input values with post method via ajax. Can I put the form inside the tr tag? How can I do that?

Here is my code:

$("button").click(function(e) {

e.preventDefault();
alert("hello");
 var formid = $(this).closest("form[id]").attr('id');;

alert(formid) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
     <form id='idForm'>
          <td><input type='input' value='12345' name='data1'></td>
          <td><input type='input' value='12345' name='data2'></td>
          <td><button type='submit' form='idForm'>Send</button></td>
     </form>
  </tr>
</table>

But when I try to check result inside Alert() it displays undefined.

Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48
gigakas
  • 9
  • 1
  • 2

2 Answers2

1

First, you have to give id or class attribute to the tags you want to manipulate. Its better to write your html like this and you can get the tag value you want with jQuery

$("button").click(function(e) {
  var input1 = $('#input1').val();
  var input2 = $('#input2').val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
     <form id='idForm'>
          <td><input id="input1" type='input' value='12345' name='data1'></td>
          <td><input id="input2" type='input' value='12345' name='data2'></td>
          <td><button type='submit' form='idForm'>Send</button></td>
     </form>
</tr>
Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48
Sir Kane
  • 71
  • 1
  • 5
0

The <button> element will have an attribute pointing to the form it's contained within, so you should be able to simply change how you get the form ID to fix the issue.

Try changing this line...

var formid = $(this).closest("form[id]").attr('id');

To something like this...

var formid = this.form.id;

Or a more jQuery way of doing it...

var formid = $(this.form).attr('id');

And, yes, you can put the <form> element in the <tr> element, however, you need to have a <td> in the <tr> as well, not have the <td> in the form.

Proper form would look more like this...

<table>
    <tr>
        <td>
            <form id="idForm">
                <input id="input1" type="input" value="12345" name="data1">
                <input id="input2" type="input" value="12345" name="data2">
                <button type="submit" form="idForm">Send</button>
            </form>
        </td>
    </tr>
</table>

Or this, which is probably closer to what you are going for...

<form id="idForm">
    <table>
        <tr>
            <td><input id="input1" type="input" value="12345" name="data1"></td>
            <td><input id="input2" type="input" value="12345" name="data2"></td>
            <td><button type="submit" form="idForm">Send</button></td>
        </tr>
    </table>
</form>
Coffee'd Up Hacker
  • 1,356
  • 11
  • 23