To capture the value of <input>
, you can use the querySelector
to, from the field selector, get your Javascript object and then use the property value
to get the current value. So:
const btn = document.querySelector('#search-submit');
const field = document.querySelector('#search');
btn.addEventListener('click', () => {
console.log(field.value);
});
<input id="search" type="text" />
<button type="button" id="search-submit">Buscar</button>
The problem is that if you concatenate the value directly to a query string from the URL, you may end up generating an invalid URL. For example, if you concatenate the string directly and the user has typed some character like ?
or &
, could invalidate your URL, add more parameters, etc - which is obviously a problem.
Therefore, you can use the function encodeURIComponent
before concatenating. See the difference:
const base = 'http://localhost:8983/solr/csv_indexing';
const query = 'foo&other_param=bar';
const withoutEncodeURIComponent = base + '/select?q=' + query;
const withEncodeURIComponent = base + '/select?q=' + encodeURIComponent(query);
console.log({ withoutEncodeURIComponent, withEncodeURIComponent });
Put it all together, you get something like:
const btn = document.querySelector('#search-submit');
const field = document.querySelector('#search');
const baseURI = 'http://localhost:8983/solr/csv_indexing';
btn.addEventListener('click', () => {
const query = encodeURIComponent(field.value);
const url = baseURI + '/select?q=' + query;
// Faça algo com `url`. (O `fetch`, por exemplo):
console.log(url);
});
<input id="search" type="text" />
<button type="button" id="search-submit">Buscar</button>
Another option to generate the URL is to use the constructor itself URL
:
const url = new URL('http://localhost:8983/solr/csv_indexing/select');
// Adicionamos o parâmetro `q`. Ele já será automaticamente "escapado":
url.searchParams.append('q', 'foo');
// Obtem a URL:
console.log(url.toString());
Do you want to redirect the user? I didn’t quite understand the question.
– Luiz Felipe
I want to add what it enters in the input at the end of that url:
"http://localhost:8983/solr/csv_indexing/select?q=
– Pirategull
And the concatenation didn’t work? I assume because of any special characters...?
– Luiz Felipe
I don’t know how to get the value that was typed in the input to add it to url
– Pirategull