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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With