I'm creating a webpage which would collect links from the user and simply open every link in a new tab. For collecting links I am using HTML's <textarea>
tag with a submit button.
User is expected to give only one link for each line
https://google.com
https://stackoverflow.com
https://facebook.com
I would open links by sending each passing each URL through this function.
function open(url) {
var open= window.open(url, '_blank');
open.focus();
}
But how exactly to run loop? How to get values from textarea
in an array and then run a loop which would send value at every index to this function?
If you think this could be done in a better than other than this, feel free to add your method.
It would help if you gave your textarea a unique identifier, this way we can get at its contents easily. ie, <textarea id="linksInput">...</textarea>
Then we can do
let links = document.getElementById("linksInput").value.split("\\n");
We get the value in the textarea and split it at every newline character ("\\n"), getting our individual links in an array, with each element being a single line from the original textarea value. Now we can loop through the array links
.
for (let i = 0; i < links.length; i++) {
open(links[i]);
}
You can add an id to the text field and use javascript to get the value of TextArea.
Since you are looking at multiple values separated by "/n"
, you will have to split the text and loop over the result.
function submitText() { var textVal = document.getElementById("txtarea").value; textVal = textVal.split('\\n'); if (textVal.length > 0) { for (const element of textVal) { console.log(element); window.open(element, "_blank"); } } }
<textarea id="txtarea"></textarea> <button type="button" onclick="submitText()">Submit</button>
You can use the below code to get your result.
HTML
<textarea id='links'>
</textarea>
<button id='trigger'> Get value </button>
JS
document.addEventListener('DOMContentLoaded', () =>{
const ta = document.getElementById('links')
const button = document.getElementById('trigger')
button.addEventListener('click', () => {
const list = ta.value.split('\n')
forEach(let i=0; i < list.length; i++) {
window.open(list[0], "_blank");
}
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.