Recipe 3.3
Adding Query Parameters to a URL
Add a query parameter to the URL by entering the name and value, then click “Add Parameter”. You can do this multiple times and the resulting URL will be updated.
Demo
Code
JavaScript
function addQueryParameter(urlString, name, value) {
const url = new URL(urlString);
url.searchParams.append(name, value);
return url.href;
}
const form = document.querySelector('#url-form');
form.addEventListener('submit', event => {
event.preventDefault();
const { url, name, value } = form.elements;
const newUrl = addQueryParameter(url.value, name.value, value.value);
url.value = newUrl;
name.value = '';
value.value = '';
name.focus();
});
HTML
<form id="url-form">
<div class="mb-3">
<label for="url" class="form-label">URL</label>
<input type="text" readonly class="form-control-plaintext" id="url" name="url" value="https://example.com/api/users">
</div>
<div class="container">
<div class="row">
<div class="col mb-3">
<label for="name" class="form-label">Parameter name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="col mb-3">
<label for="value" class="form-label">Parameter value</label>
<input type="text" class="form-control" id="value" name="value">
</div>
</div>
<button class="btn btn-primary">Add Parameter</button>
</div>
</form>