Accept relative URLs in HTML5 url inputs
HTML
<p>The HTML5 <code>url</code> input type is great, except that it doesn't accept relative/hostless URLs which are useful to be able to enter. However, it's easy to support these by adding a <code>change</code> event handler that puts the URL value into an anchor's <code>href</code> content attribute and then immediately extract the <code>href</code> DOM property for use as the field's value—a slick hack that uses the browser's URL normalization found in the HTMLAnchorElement interface.</p>
<form onsubmit="alert('Valid!'); return false;">
<p>
<label for=url>URL:</label>
<input id=url name=url type=url placeholder="Try entering a relative URL or an absolute one without a host name." />
<button type=submit>Submit</button>
</p>
</form>
<footer>
<address><a href="http://weston.ruter.net/" rel=author target=_blank>Weston Ruter</a> @ <a href="http://x-team.com/" target=_blank>X-Team</a> / <a href="http://xhtmlized.com" target=_blank>XHTMLized</a></address>
</footer>
CSS
body {
margin: 1em;
}
:valid {
border: solid 1px green;
}
:invalid {
border: solid 1px red;
}
#url {
width: 400px;
}
p {
margin-top: 1em;
margin-bottom: 1em;
}
footer {
display:block;
margin-top:1em;
border-top:solid 1px gray;
padding-top:0.5em;
font-size:smaller;
font-style:italic;
}