Reputation: 23
I have this code that works fine but I want to make sure that when users type in a url and then click on the link it takes them to the url they typed.
The problem that I am having is that when users type in their url, based url is being appended to the url they typed. For example if users type in espn.com they get fiddle.jshell.net/BMDKr/5/show/espn.com. I just want espn.com.
Can someone please advise?
<input type="text" id="text"> <a href="#" id="link" target="_blank">Link</a>
$(function () {
// When the input field changes value
$('#text').blur(function(){
// Set the attribute 'href' of the link to the value of the input field
$('#link').attr('href', $('#text').val());
});
});
Upvotes: 2
Views: 40
Reputation: 2113
You want to check if http:// is in the url they entered, and if not, you want to prepend it before setting the href on the link. You can use a regular expression to check for http:// and https://. Here is a basic example:
var url = $('#text').val();
if (!url.match(/^https?:\/\//i)) {
url = 'http://'+url;
}
Upvotes: 1