I was wondering if it is possible to have an input field that has a bit of text added to it after the user enters the information they want. EX. a user types youtube.com into a search bar, and the input applies https://www.
3 Answers
You could use an event listener that will change the value of the input field.
Use RegEx to find out if the string (https://www.) has been set before (for instance by copying and pasting the URL).
Here is an example:
document.getElementById('url').addEventListener('keyup', (e) => {
if (!/^(https:\/\/www.)/.test(e.target.value) && e.target.value) {
e.target.value = `https://www.${e.target.value}`;
}
});
<input type="text" id="url">
Comments
use blur event you can run a function after a user leaves the input field
Comments
You need to manipulate the user input for that use javascript. If user presses submit button then don't submit input immediately use event.preventDefault() to stop default action and then change user input if needed after that manually submit it using AJAX.
function manuallySubmit(event){
event.preventDefault();
// manipulate input here
var input = document.getElementById("input").value;
input = "changed value " + input;
console.log(input);
/* AJAX POST request
let xhr = new XMLHttpRequest();
xhr.open('POST','location',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8');
data = 'input='+(input);
xhr.send(data);
*/
// window.location.href="newlocation" if you want to redirect
}
<form onsubmit="manuallySubmit(event)" action='#' method="POST">
<input type="text" name="input" id="input" /><br/>
<input type="submit">
</form>
submitevent listener.