Manipulate Array Params of URL Query String
Tldr: URL.searchParams
<!-- some legacy erb -->
<dl>
<% if @selected_price_ranges %>
<% @selected_price_ranges.each do |content| %>
<dd>
<%= content %>
<span class="icon-close"
data-key="price_ranges[]"
data-value="<%= content %>"></span>
</dd>
<% end %>
<% end %>
</dl>
<script>
$(function () {
$('dl dd span.icon-close').on('click', function(e){
if (typeof URL !== 'undefined') {
let url = new URL(window.location.href)
let key = $(this).data('key')
//console.log(url.searchParams.getAll(key))
let newValues = url.searchParams.getAll(key)
.filter( value => value !== $(this).data('value') )
url.searchParams.delete(key)
for (newValue of newValues) {
url.searchParams.append(key, newValue)
}
//console.log(url.searchParams.getAll(key))
window.location = url
} else {
console.log(`Your browser ${navigator.appVersion} does not support URL`)
}
});
})
</script>
Reference
Easy URL Manipulation with URLSearchParams