Reputation: 707
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.
Upvotes: 4
Views: 2678
Reputation: 236092
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.
Upvotes: 2
Reputation: 30197
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'));
});
});
Upvotes: 1
Reputation: 66465
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)
Upvotes: 3
Reputation: 344675
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"
Upvotes: 1