0

Hello friends I have a text input and a button In Input Text, a link is entered, for example, the link of an Instagram post After entering the link, I want to go to the link by clicking the button How do I do this with JavaScript?

  <div class="container">         
        <div class="main">
          <input type="text" placeholder="https//:www.instagram.com/..."
          id="link">
    
     <button id="button-1"><a href="#">go</a></button>       
        </div>
    </div>

1 Answers1

-1

Capture the URL on the blur event and apply it to the link. You can validate for a valid URL this way as well.

window.addEventListener('load', () => {
  document.querySelector('#link').addEventListener('blur', el => {
    if (!el.target.value.includes('http')) {
      alert('Please enter a valid URL')
      return;
    }
    document.querySelector('#go-link').setAttribute('href', el.target.value)
  })
})
<div class="container">
  <div class="main">
    <input type="text" placeholder="https//:www.instagram.com/..." id="link">
    <a href="#" id='go-link' target="_blank">go</a>
  </div>
</div>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • This question may be a duplicate, but the linked duplicate solution isn't really applicable to this question, so I'm posting an answer regardless – Kinglish Jul 09 '21 at 19:01