简体   繁体   中英

Getting the text within an input box

How can I get the text within an input box and go to the page ending with it? For example, if someone types "home" in an input box it directs the user to the URL https://mysitename.com/home .

You can do this using document.location.href .

 let btn = document.querySelector('button'); let ipt = document.querySelector('input[type=text]'); btn.onclick = function() { document.location.href = "https://mysitename.com/" + ipt.value; }
 <input type="text" placeholder="link name"> <button>go</button>

You can check this solution. This will append the input value to your current host name .

If you want predefined hostName then your can set the value to this variable. const hostName = "your host name here"

You can use window.location.href = yourNewUrl to redirect to new address. I've commented out the redirection line. You need to uncomment that.

 const form = document.querySelector('#myForm'); const inputField = document.querySelector('#name'); form.addEventListener('submit', handleSubmit); function handleSubmit(event) { event.preventDefault(); const pageName = inputField.value; inputField.value = ''; const hostName = window.location.hostname; const url = `${hostName}/${pageName}`; console.log(url); // window.location.href = url; }
 <form id="myForm"> <input type="text" id="name" placeholder="type name and hit enter"> </form>

Simply type and direct to that link

by .addEventListener event change as you wish,

 var mySearchInput = document.getElementById('mySearchInput'); mySearchInput.addEventListener('blur', (event) => { document.location.href = "https://mysitename.com/" + mySearchInput.value; })
 <label>Link</label> <input type="text" id="mytext" placeholder="Type link here..." />

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM