Beldion Bryan Balanan Beldion Bryan Balanan - 5 months ago 7
jQuery Question

Displaying data-message in a textarea



$(document).ready(function() {
$('textarea').val($('textarea').data('message'));
});

.testtextarea {
outline: none;
resize: none;
}

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>
<h2>Test Page</h2>
<textarea class="testtextarea" data-message="Hello World"></textarea>
<textarea class="testtextarea" data-message="Test Text Area"></textarea>
<textarea class="testtextarea" data-message="Hello Universe"></textarea>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</html>





Anyone here knows how to fix this issue? the only
data-message
it is showing is the
data-message
for the first one. What I am trying to do here is to make it show its respective data message per
textarea
.

Thanks

Answer

Loop through all textarea and set value accordingly using $(this)

$( document ).ready(function() {
  $('textarea').each(function() {
    $(this).val($(this).data('message'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<h2>Test Page</h2>
<textarea class="testtextarea" data-message="Hello World"></textarea>

<textarea class="testtextarea" data-message="Test Text Area"></textarea>

<textarea class="testtextarea" data-message="Hello Universe"></textarea>