views:

67

answers:

4

I have a textarea with a default value of http://. Now when an user pastes in an url (if they don't know what they are doing, like most people) it comes out like this http://http://www.google.com. I've seen a site that as soon as you have http://http:// it removes one via JavaScript.

I am not familiar with JavaScript, so can anyone help me?

I don't want to clear the field on focus only.

+2  A: 

Keeping it simple and using the replace function:

var url = "http://http://google.com";
url = url.replace("http://http://","http://");

... this will basically replace the first string "http://http://" by the second, "http://".

You'll need to call this when the content of the field change. For instance using jQuery:

$("#myfield").change(function(e){
  $(this).val($(this).val().replace("http://http://","http://"));
});

without jQuery (not 100% sure about this):

document.getElementById("myfield").onChange = function(){
  var val=document.getElementById("myfield").value;
  document.getElementById("myfield").value = value.replace("http://http://","http://");
}

Unrelated but worth mentioning: This is not AJAX, it is simple javascript. Ajax is the term used when you try to have asynchronous communication with a server using the XMLHTTP object

Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page.

(via)

marcgg
The question here is, when to call that?
jAndy
@jandy: I didn't quite got it from the question, but here's an edit
marcgg
+1  A: 

Always nice to have a none regex option (saving those precious micro-seconds!):

var url = "http://http://google.com";
url = url.substring(url.lastIndexOf("http://"));

// -> "http://google.com"
Andy E
+1  A: 

You do not need ajax to do that just simple javascript can do the trick.

jQuery(document).ready(function(){

    jQuery('#idofurtextfield').blur(function(){

        jQuery(this).val(jQuery(this).val().replace(/(http:\/\/)\1/, '$1'));

    });

});
sushil bharwani
this worked like a dream!!! thanks
loo
A: 

No Ajax at all to do that kind of magic.

This will do it:

$(function(){
  $('textarea').bind('keydown', function(e){
    var $this = $(this);
     if(e.which === 86 && e.ctrlKey){
       setTimeout(function(){
          $this.val($this.val().replace(/http:\/\/http:\/\//,"http://"));
       }, 1);
     }
  });
});​

This will replace http:// on ctrl+v if already exists. You might also want to call the same routine on a change event if an user uses a contextmenu to paste.

jAndy
aha, pretty cool! would that work in IE? not sure about e.ctrlKey
marcgg
e.ctrlKey should be normalized through jQuery, so yes. Should work crossbrowser.
jAndy
yes but without jQuery?
marcgg