Thursday, November 28, 2013

Adding parameters to an existing link

I'm working on a project where the user selects a date and then clicks a link.  The date needs to be added as a parameter to the link's url.  The normal way to do this would be with a form.  But each link would then have to be a submit button.  I don't want them to look like submit buttons.  But I also don't want to restyle them to look like links.  So I set out to find a way to dynamically add the date to each link.

Turns out with jquery it's pretty easy.  Check it out...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('a').click(function() {
$(this).attr('href', function(i, h){
return h + '?date=' + $('#date').val()
})
alert($(this).attr('href'))
})
})
</script>
</head>
<body>
<div id="dateDiv">
<select id="date">
<option value="2013-11-01">Nov 2013</option>
<option value="2013-10-01">Oct 2013</option>
<option value="2013-09-01">Sep 2013</option>
</select>
</div>
<ul id="linkList">
<li><a href="/report/1">Report 1</a></li>
<li><a href="/report/2">Report 2</a></li>
<li><a href="/report/3">Report 3</a></li>
<li><a href="/report/4">Report 4</a></li>
</ul>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
Update: okay, another easy way to do this would be to leave the links as links but put the parameters, including the date, in a form, then trap the click event on the link and submit the form. But what's cool about that?