Script to look for http:// or https:// in input box on keyup and remove it

Viewed 42

I need to allow members to enter in a URL but I want to remove any http:// or https:// they enter into the URL and keep the rest.

Here is the code I have that's not working:

document.addEventListener("DOMContentLoaded", function() {
  const $input = document.querySelector('.inputbox');

  if ($input) {
    $input.addEventListener('keyup', () => {
      $input.value = $input.value.replace('http://', '');
      $input.value = $input.value.replace('https://', '');
    })
  }
});
.inputbox {
  width: 100%;
  max-width: 350px!important;
  font-size: 17px;
  padding: 3px!important;
  color: #000!important;
  border-style: solid!important;
  border-radius: 5px!important;
  border-color: #000!important;
  border-width: 1px!important;
}
<form name="myForm" method="post" action="funnel">
  <select class="selectbox" name="preurl">
    <option value="http://">http://</option>
    <option value="https://">https://</option>
  </select><input type="text" name="url" class="inputbox" value="" placeholder="URL:" required><br /> Enter the URL you wish people to goto after filling out your form<br /><br />
  <br /><br />
  <p><input type="submit" name="submit" class="btn-success" value="Save Settings" /></p>
</form>

1 Answers

Here is the point.

In vanilla JavaScript, each event type requires its own event listener. Unfortunately, you can’t pass in multiple events to a single listener like you might in jQuery and other frameworks.

So, for the problem you can solve it like this:

// Setup function
const removeHttp = function (event) {
    event.target.value = event.target.value.replace('http://', '');
    event.target.value = event.target.value.replace('https://', '');
};

document.addEventListener("DOMContentLoaded", function() {
  const input = document.querySelector('.inputbox');
  if (input) {
    // Add listeners
    input.addEventListener('change', removeHttp, false);
    input.addEventListener('keyup', removeHttp, false);
    input.addEventListener('paste', removeHttp, false);
  }
});
<form name="myForm" method="post" action="#">
<input type="text" name="url" class="inputbox" value="" placeholder="URL:" required><br />
</form>

Related