Shiraz Ahmad
Shiraz Ahmad

Reputation: 105

Value of Data-id to be value of parent element

I just want the data-id value to be what's written in the textarea means parent element.

<textarea aria-label="Add a comment…" placeholder="Add a comment…" class="addcomment_ta" autocomplete="off" autocorrect="off" id="comment_i" name="comment_content" id="editable_comment" data-id='TEXTAREA VALUE'></textarea>

Upvotes: 0

Views: 120

Answers (1)

user10791031
user10791031

Reputation:

Try this:

$('.addcomment_ta').on("keyup", function() {
  $(this).attr('data-id', $(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea aria-label="Add a comment…" placeholder="Add a comment…" class="addcomment_ta" autocomplete="off" autocorrect="off" name="comment_content" id="editable_comment" data-id='TEXTAREA VALUE'></textarea>

I created a keyup function in JQuery so every time you start typing the data-id updates!

UPDATE: The previous example does not work with copy, pasting and cutting. I changed the keyup to a change, keyup, paste

$('.addcomment_ta').on('change keyup paste', function() {
  $(this).attr('data-id', $(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea aria-label="Add a comment…" placeholder="Add a comment…" class="addcomment_ta" autocomplete="off" autocorrect="off" name="comment_content" id="editable_comment" data-id='TEXTAREA VALUE'></textarea>

Upvotes: 2

Related Questions