0

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.

1
  • You can do it in the form's submit event listener. Commented Sep 6, 2019 at 23:13

3 Answers 3

1

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">

Sign up to request clarification or add additional context in comments.

Comments

0

use blur event you can run a function after a user leaves the input field

see https://www.w3schools.com/jsref/event_onblur.asp

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.