Irfan Sindhi
Irfan Sindhi

Reputation: 75

How to get text of form child when an input element is clicked on

This is my HTML layout. I have multiple forms:

 <table>
     <form>
         <tr>
             <td id="1">Text1</td>
             <td id="2">Text2</td>
             <input type="button" value="Submit" id="submit1">
         </tr>
     </form>
     <form>
         <tr>
             <td id="1">Text1</td>
             <td id="2">Text2</td>
             <input type="button" value="Submit" id="submit2">
         </tr>
     </form>

</table>

What I want is to fetch the text in between the <td> of id=1. What I have done is:

$(document).ready(function(){
    $('[id*="submit"]').on('click', function() {
        console.log($(this).closest("form").find('td first').text());
    }); 
});  

Upvotes: 2

Views: 1232

Answers (3)

Haze
Haze

Reputation: 196

You should may be prefer class than id, iike what Julia Finarovsky said, id should be unique.

You almost got it right, though you just forgot : in between td and first in the find param

$(document).ready(function(){
    $('[id*="submit"]').on('click', function() {
        console.log($(this).closest("form").find('td:first').text());
    }); 
}); 

Hope this helps.

Upvotes: 0

Shiladitya
Shiladitya

Reputation: 12161

Here you go with a solution

$(document).ready(function(){
  $('[id*="submit"]').on('click', function() {
    console.log($(this).closest('form').find('td').first().text());
  }); 
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <table>
    <tr>
      <td id="form1-1">Form 1: Text1</td>
      <td id="form1-2">Text2</td>
       <input type="button" value="Submit" id="submit1">
     </tr>
 </table>
</form>
<form>
 <table>
   <tr>
     <td id="form2-1">Form 2: Text1</td>
     <td id="form2-2">Text2</td>
     <input type="button" value="Submit" id="submit2">
   </tr>
  </table>
</form>

There are few thing to notice in your code

  • id should be unique
  • form tag should be outside the table

Hope this will you.

Upvotes: 1

Julia Finarovsky
Julia Finarovsky

Reputation: 21

You almost got it right! It should be

$(this).closest("form").find('td#1').text()

You might consider not using id's in this context; they are meant to be unique.

Upvotes: 1

Related Questions