altaccount forwork
altaccount forwork

Reputation: 21

Add text to an input and then append to a text box with text already in it?

I'm trying to make a JavaScript/jQuery script that adds text from an input to an anchor tag with text already in it. Here's an example of what I'm trying to accomplish:

<!-- BEFORE INPUT HAS BEEN PRESSED -->
<a> Add an attachment for https://thislink/ </a>
<br>
<!-- AFTER INPUT AS BEEN USED AND SUBMIT WAS PRESSED -->
<a href="https://thislink/[text-from-input]"> [text-from-input] </a>
<form>
   <input> text from this will be added to the text area </input>
   <input type="submit" value="Submit"></input>
</form>

Upvotes: 2

Views: 67

Answers (3)

Deepak
Deepak

Reputation: 2742

You can make use of id attribute to get the container to hold your anchor tag and then update its anchor tag dynamically with any value user has written:

function changeLink() {
  document.getElementById("dynamic-link").innerHTML = `<a href='https://thislink/${document.getElementById("user-input").value}'>Link Generated</a>`
}
<div> Add an attachment for https://thislink/ </div>
<br>
<div id="dynamic-link">
</div>
<br/>
<form>
  <input type="text" id="user-input" />
  <br/><br/>
  <button type="button" onclick="changeLink()">Submit</button>
</form>

Upvotes: 0

Mah Es
Mah Es

Reputation: 630

give your a and input an id. use javascript to get the input value. then use innerHTML to append the input value to the a text.

function appendText(e){
      e.preventDefault();
       var inputValue = document.getElementById('input').value
        document.getElementById('theLink').innerHTML += inputValue
}
 <a id="theLink" href="https://thislink/[text-from-input]"> [text-from-input] </a>
<form>
     <input id="input"> text from this will be added to the text area </input>
     <input onclick="appendText(event)" type="submit" value="Submit"/>
 </form>


     

Upvotes: 0

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8158

You can select the required elements from the DOM and then add a listener to when the form is submitted and in the event handler simply grab the contents of the input and update the DOM.

Following example will help you get started. Also, it's always a good idea to sanitize user input before using it.

const link = document.querySelector(".link");
const form = document.querySelector(".form");

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const userInput = e.target.elements["attachment-input"].value;
  link.href = `https://thislink/${userInput}`;
  link.textContent = userInput;
});
<a class="link">Add an attachment for https://thislink/</a>
<br>
<form class="form">
   <label for="attachment-input">Enter Attachment</label>
   <input type="text" id="attachment-input">
   <input type="submit" value="Submit">
</form>

Upvotes: 1

Related Questions