I’m listing some user generated links on a page. The problem is that not all users are adding “http://” to their urls, which is messing things up.
In response to this I’ve used this piece of jQuery (“$” replaced with “jQuery” due to noconflict mode) to try to detect whether http:// is present and add it if it’s not:
jQuery('.theirsite').each(function(){
var currentlink = jQuery(this);
var linkloc = currentlink.attr('href');
var httpcheck = linkloc.substr(0,7);
if(httpcheck!="http://"){
currentlink.attr('href','http://'+linkloc);
}
});
But it’s not working, and I’m seeing this error in Chrome’s console:
Uncaught TypeError: Cannot read property 'substr' of undefined (index):456
(anonymous function) (index):456
x.extend.each jquery.js:3
x.fn.x.each jquery.js:3
(anonymous function)
This is the php I’m using:
<div class="theirsite"><?php echo '<a href="' . $user_info->user_url . '" class="button"> Visit their website </a>';?></div>
The whole thing is on WordPress. Apologies if I’ve left anything out or not seen anything obvious. All pointers appreciated.
Your
.theirsite
element does not have anhref
attribute, it is adiv
.You should change:
to something like:
maybe this will do:
first of all, i declare jQuery to $, so you dont have to type jQuery all the time.
then comes the ready handler.
then the each part, where you look up the a element and check, if the url contains http://
i also wrote the check for https. should work..