3

i am using an HTML5 input field on a get form to implement search on my site:

<input type="search" name="q" placeholder="search" value="">

everything works, but after the first search the search string the user entered is not saved in the search field, rather the placeholder attribute value is displayed again.

after the first search i would like to have the search string the user entered displayed in the search field on the form.

that means that value attribute of the input field needs to be "" before the first search (so that the placeholder attribute value will display) and then dynamically updated after the first search.

I understand from the Mozilla documentation on <input type="search"> that the value the user entered is stored in the DOMstring "searchTerms = mySearch.value;" but my programming skills and experience are limited.

i am not using php, thank-you in advance.

2 Answers2

0

Try adding this event.preventDefault(); on your function, with that your event will be canceled but the propagation of it won't. If you want to learn more about it, here's the documentation: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

0

solved the problem with:

  • DOMContentLoaded to trigger the javascript

(https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event)

  • URLSearchParams and URLSearchParams.get() to get query string

(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get)

  • getElementById to set value in input field

(https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)

it is a common question-

(How can I get query string values in JavaScript?)

<input type="search" name="q" placeholder="search" id=mySearch required value="">

<script type="text/javascript">
window.addEventListener('DOMContentLoaded', (event) => {
    let params = new URLSearchParams(document.location.search.substring(1));
    let qstring = params.get("q"); // is the string for the query
    document.getElementById("mySearch").value = qstring;
});
</script>