stoerebink stoerebink - 4 months ago 23
Ruby Question

How to add/remove params to link with jquery

I have some select fields that set for example the vendor-id and status for my datatable. When these field change, I want to include these parameters in a link (the link calls a server function that exports the data to csv). My experience with jquery/coffeescript is very limited and I'm having trouble getting this to work. What I have so far is:

$ ->
$('#vendor-id').on 'change', ->
$('#shipments-table').DataTable().ajax.reload()
$('a.download-link').attr 'href', (index, href) ->
param = 'vendor-id='+$('#vendor-id').val();
if href.charAt(href.length - 1) == '?'
href + param
else if href.indexOf('?') > 0
if href.indexOf(param) == 0
href + '&' + param
else
href + '?' + param
return


I have two problems with my code. One is that for some reason, when I change the value, the param is added to the link twice (example: http://link.com?vendor-id=1&vendor-id=1 )

The second problem is that when I select a different value for this select box, the previous value is not removed from the link but added on to it.

How can I fix this?

Answer

You can find some answers here: Change URL parameters. For example: http://stackoverflow.com/a/10997390/4335261 - it worked for me. Just copy updateURLParameter function and use it this way:

$ ->
   $('#vendor-id').on 'change', ->
   $('#shipments-table').DataTable().ajax.reload()
   $('a.download-link').attr 'href', (index, href) ->
     updateURLParameter(href, 'vandor-id', $('#vendor-id').val())