1

I have a jQuery form with a text field (Field ID is: 43) for a website URL. When a user inputs either "http://" or "https://" as part of the URL, I need the form to automatically remove the "http://" or "https://" portion before or when the form is submitted.

I cannot seem to get this working. Here is the latest code I have tried (at first, just trying to get it working to remove "http://"

<script type="text/javascript">
               document.getElementById("43").setAttribute("onchange", "deleteValue()");
function deleteValue() {
    var weburl = 'http://';
    var textarea = document.getElementById("43");
    var data = textarea.value;
    textarea.value = textarea.value.replace(weburl.value, "");
}
</script>

Can anyone provide a suggestion as to how I can get this working?

Bryan Earl
  • 27
  • 5
  • Have you seen [this answer here](https://stackoverflow.com/questions/8206269/how-to-remove-http-from-a-url-in-javascript)? – crazymatt May 14 '18 at 20:03
  • That looks promising, but I do not know enough about the coding. Can you tell me how would I write that out as a complete "script" to add to a page? – Bryan Earl May 14 '18 at 20:19

1 Answers1

0

You can use the .blur() event to trigger the removal of http:// and https://

Working Example:

$(document).ready(function(){
    
    $('input').blur(function(){
        var currentText = $(this).val();
        var replacedText = currentText.replace(/^https?\:\/\//i, '');
        $(this).val(replacedText);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<fieldset>
<legend>Write a url with http:// and click elsewhere</legend>
<input type="text" name="myUrl" />
</fieldset>
</form>
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • I can see by running your snippet that the code works as expected, but I can not for the life of me figure out how to apply it to my form. when I add it as a javascript to the page, it has an error in the console: "Uncaught TypeError: $ is not a function" – Bryan Earl May 14 '18 at 21:00
  • What version of jQuery is your page referencing? – Rounin May 14 '18 at 21:06
  • 1
    Thank you!!! I had it placed in the wrong included PHP file and ALSO needed to specifically include the version 2.1.1 as you did in your example. Thank you! – Bryan Earl May 14 '18 at 21:45