Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
InvalidSyntax Avatar asked Sep 13 '26 20:09

InvalidSyntax


2 Answers

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>
like image 65
The Process Avatar answered Sep 15 '26 09:09

The Process


I think this does not refer to what you are expecting.

try this :

$('td[data-label]').each(function() {
  $(this).children('input').attr('placeholder', $(this).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>
like image 21
Apolo Avatar answered Sep 15 '26 10:09

Apolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!