Home > OS >  add text to an input and then append to a text box with text already in it?
add text to an input and then append to a text box with text already in it?

Time:12-19

I'm trying to make a JavaScript/jQuery script that adds text from and inputs to an a href 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>

CodePudding user response:

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 >Add an attachment for https://thislink/</a>
<br>
<form >
   <label for="attachment-input">Enter Attachment</label>
   <input type="text" id="attachment-input">
   <input type="submit" value="Submit">
</form>

CodePudding user response:

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>


     

CodePudding user response:

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>

  • Related