I created this fiddle so that you can see the struggle I have.
My HTML
<form action="" method="post" role="form" name="my-form-name">
<button class="html-button">Link me</button>
<textarea name="x" id="post-text" rows="17" required="required"></textarea>
<button type="submit" class="submit-button-form">submit form</button>
</form>
JS:
$(".html-button").on("click", function () {
var urls = prompt("Add a link", "http://");
var setText = $("#post-text").val(urls);
// Adding prompt text into my input field
$("#post-text").val(urls);
});
This code works, but it only works once. Meaning: if I add a hyperlink it works the first time, but when I want to add another link, it doesn't insert it. Instead, it just changes whatever I had put in first + the additonal plain text I am adding to the textarea.
My question: how can I make this link addition independent of what I type in the textarea (plain text) and make sure that I can add more links without it changing the other ones in the textarea?
Fiddle: https://jsfiddle.net/vaxqsztj/1/
You need to append data instead of replacing
$("#post-text").val(urls); <-- here you're replacing data with url only
instead you need to add previous text along with url
var setText = $("#post-text").val(urls);
$("#post-text").val(setText + urls); <-- adding url along with previous value
$(".html-button").on("click", function() {
var urls = prompt("Add a link", "http://");
var setText = $("#post-text").val();
// Adding prompt text into my input field
$("#post-text").val(setText + urls);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" role="form" name="my-form-name">
<button class="html-button" type='button'>Link me</button>
<textarea name="x" id="post-text" rows="17" required="required"></textarea>
<button type="submit" class="submit-button-form">submit form</button>
</form>