Most of the solutions I have found deal with localized javascript instead of an external file so I am posting this question. Links to attempted solutions:
Turn HTML Form Input into JavaScript Variable
I want to take a html form input and use that input in an external javascript file.
The html form input comes from index.html
<script src="script/our.js"></script>
<div class="searchbar">
<form action="">
<input type="text" placeholder="search ..." name="query" onchange=formChange()>
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
var searchThis = document.getElementsByName("query").value;
}
</script>
Then, our.js tries to use the variable like so:
var Manager;
(function ($) {
$(function () {
Manager.store.addByValue('q', searchThis);
});
})(jQuery);
With my current setup, if I searched a term ("unlock") the form will send and the page will show it has found 0 documents. It does not say that searchThis
is undefined
The back end of my js works with searchThis
being replaced by "*:*"
to display all records instead of those with the searched string.
EDIT #1 : Manager.jquery.js
to see if I need to allow for search term to be a variable an not just a string
REDACTED
EDIT #2 : I have been trying suggestions below. Currently:
index.html
changed
<script>
function formChange(){
var searchThis = document.getElementsByName("query")[0].value;
console.log(searchThis);
window.searchThis = searchThis;
console.log(window.searchThis);
}
</script>
our.js
changed
Manager.store.addByValue('q', window.searchThis);
The console.log
s in index.html
return my search term. However if I do the same just before window.searchThis
is called in our.js
it returns as undefined.
EDIT #3
I have been playing with importing the searchThis
variable. I cannot import window.searchThis
because I get an error for unexpected .
In full when I try:
import searchThis from "../index.html"
It gives me an error stating:
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
EDIT #4 : my <form>
+ <script>
section with adjustments
<div class="searchbar">
<form>
<input type="text" placeholder="search Nicola..." name="query" onsubmit=formChange() >
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
searchThis = document.getElementsByName("query")[0].value;
term = searchThis;
console.log(term);
}
</script>
<script defer="defer" src="script/our.js" type="module"></script>
Ive added my form section because I could be doing something wrong here too. When I go to my main page the console.log
on our.js
has already been logged as undefined. When I enter a search term with onchange
instead of onsubmit
the console logs from my <script>
. Once I hit submit, the page flashes and the log for our.js
is again at the top and undefined.