0

I have textarea and I want to detect when the user will finish TYPING or PASTING a url. I want to catch that url an send it to php.

I looked at many solutions from google, but they all seems to add a anchor tag around the link which I don't want to do.

I tried using this regexp I found in a solution on this website, but it did not work:

/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/

the problem with it is that as soon I type something like http://, it will automatically send that string only.

I don't want to write a regexp with finite list of TLDs. What ways can I archive this?

this is the code:

$(document).ready(function() {
    $('#write-post-textarea').keyup(function() {    
        if(isUrl($(this).val())){
           //Show the url in an alert box
           alert($(this).val());
        }else{
           //do something if its not a url
        }
    });     
    function isUrl(s) {
        //var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        return regexp.test(s);
    }    
});
1
  • 1
    try to add code in keyup event that match last key as space or enter before validating url. Commented Aug 3, 2014 at 5:40

2 Answers 2

1

Use keyup event along with keycode validation to make sure enter or space button pressed before start validation.

$("#write-post-textarea").keyup(function (e) {
    if (e.which == 13 || e.which == 32) { // 32 may be for space bar click
        if(isUrl($(this).val())){
          //Show the url in an alert box
          alert($(this).val());
        }else{
          //do something if its not a url
        }
     }
});
Sign up to request clarification or add additional context in comments.

Comments

0

I think the problem you have is that whenever you press a key it checks url once. So as soon as you type in something that matches the regexp it sends. You can try set a timer like this:

var timer;
$(document).ready(function() {
    $('#write-post-textarea').keyup(function() {
        var $this = $(this);
        clearTimeout(timer);
        setTimeout(function ()}
          if(isUrl($this.val())){
             //Show the url in an alert box
             alert($(this).val());
          }else{
             //do something if its not a url
          }
        }, 2000);
    });

    function isUrl(s) {
        //var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        return regexp.test(s);
    }

});

So that timer will be clear when you are typing, and only run the code when you stop.

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.