Imran Imran - 7 months ago 13
Javascript Question

Populating child attribute using jQuery

I have table which contains

<td>
's with
data-label
attributes.
Using jQuery I would like to populate the child
input
tag
placeholder
tag.

HTML:

<table>
<tr>
<td data-label="Some placeholder text goes here"><input type="text"></td>
</tr>
<tr>
<td data-label="Some placeholder text goes here"><input type="text"></td>
</tr>
<tr>
<td data-label="Some placeholder text goes here"><input type="text"></td>
</tr>
</table>


JS:

$('td[data-label]').children('input').attr('placeholder', $(this).data('label'));


Using this code above, the placeholders are not set, could someone tell me what I'm doing wrong here?

Answer

You need .data() from the td, as your input doesn't have a data-label attr. So you can use .closest('td') to refer td's data

$('td[data-label] input').attr('placeholder',function(){
  return $(this).closest('td').data('label');
});  

Check the below snippet:

$('td[data-label] input').attr('placeholder', function() {
  return $(this).closest('td').data('label');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td data-label="Some placeholder text goes here">
      <input type="text">
    </td>
  </tr>
  <tr>
    <td data-label="Some placeholder text goes here">
      <input type="text">
    </td>
  </tr>
  <tr>
    <td data-label="Some placeholder text goes here">
      <input type="text">
    </td>
  </tr>
</table>

Comments