0

I've got an <input> tag inside a <table> with a custom attribute. When I try to create a function to retrieve that attribute it doesn't work. Any ideas?

<table>
  <tr>
    <td>
      <input row="ab01" id="ab01_01">
    </td>
  </tr>
</table>

function retrieve_row(){
alert($(this).attr('row'));
}

The result is undefined. Why?

1
  • 3
    because what is $(this)? try $("#ab01_01").attr('row'); Commented Oct 24, 2013 at 12:00

1 Answer 1

3

A couple things:

Your this isn't scoped right, just target your element directly:

function retrieve_row(){
   alert($('#ab01_01').attr('row'));
}

Also, don't make custom HTML attributes like you are. Have no fear, though, you can use the HTML5 data- attribute to achieve the same end:

  <input row="ab01" id="ab01_01">  //INVALID

  <input data-row="ab01" id="ab01_01"> //VALID

   function retrieve_row(){
      alert($('#ab01_01').attr('data-row')); //The un-hip way
      alert($('#ab01_01').data('row')); //Like the cool kids are doing
   }

From jQuery's pappy: http://ejohn.org/blog/html-5-data-attributes/

Based on the OP's comments, I believe he is looking for this:

$("table").on( "click", "input", function() {
     alert($(this).data('row'));
});

You might want to add a class or ID to your table so that this function isn't overly broad.

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

6 Comments

I think you mean attribute, not element?
+1 Although using data attributes, you should use .data() instead of .attr()
You both are right on both counts. Sorry, early morning and had blood taken :)
it is working, but: 1- if I have multiple input tag with different id and different data-row attribute and 2- I make a function onclick that retrieve me the data-row of the input I've clicked?
Are you looking for a click handler to be applied to each input, which will alert you to its data-row value?
|

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.