Reputation: 55
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>
Upvotes: 0
Views: 643
Reputation: 3230
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
Upvotes: 1
Reputation: 20431
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);
Upvotes: 2