0

I'm attempting to use the window.open command to open a new tab with the input given by the user. I'm having trouble getting it to work, Here's my code:

const myButton = document.getElementById('add')
myButton.addEventListener('click', function(event2) {
  window.open('link');
})
<input id="link" />
<button id="add">Add</button>
Daweed
  • 1,419
  • 1
  • 9
  • 24
Max Singer
  • 55
  • 7

2 Answers2

2

Your syntax is not correct. You are trying to open 'link'. It is not even a variable, just a string.

Use querySelector or a selector like getElementById and then get the value.

let inputVal = document.querySelector('#link').value;
//Manipulate your URL, add https:// or replace http:// with https:// or add www:



window.open(manipulatedValue);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
1

This can't be really demonstrated in a stackoverflow example, due to how it's sandboxed. But you can try something like below:

const link = document.getElementById("link");
const button = document.getElementById("add");
button.addEventListener("click", event => {
  const url = link.value;
  window.open(url);
});

Regarding the URL comment, there's no real easy way to validate if a string is a valid URL or not. Here's an answer that attempts to check that via Regular Expressions:

Check if a JavaScript string is a URL

GenericUser
  • 3,003
  • 1
  • 11
  • 17
  • Added additional information regarding URL validation. To be honest, there isn't an easy way. You'll have to set up some validation that will check the input string. I added a link from another stack overflow question that has a means to solve that with regex. – GenericUser Jun 14 '21 at 19:32