Lucy Posted February 22, 2015 Share Posted February 22, 2015 I'm working on a search function. I have a paragraph and an input field beneath it for a user to type a search term into, which should then be stored as a variable upon submitting. This should be really simple, right? It doesn't work though. If I set a default value, it uses that as the variable, otherwise I get 'an empty string' - it just won't save what has been typed in. Here's the HTML for the search box and submit button: <input type="text" name="term" id="searchterm" /><input type="submit" name="enter" value="Enter" /> And for the variable to be used to search with: var searchTerm = document.getElementById("searchterm").value; I've tried variations and even tried to use a function for the onsubmit event, but nothing works. I think I sort of get why it shouldn't work - once the information is submitted the page will reload which will reload the Javascript, and it can only get the value the input box has at the time of the page load... but Google results seem to say it should work anyway. As usual, I'm probably missing something. Can anyone help? Many thanks Link to comment Share on other sites More sharing options...
Ingolme Posted February 22, 2015 Share Posted February 22, 2015 The variable searchTerm doesn't update automatically when the field changes. You need to assign document.getElementById("searchterm").value to it every time that you want to check the field's value. Link to comment Share on other sites More sharing options...
davej Posted February 23, 2015 Share Posted February 23, 2015 There was a similar recent thread... http://w3schools.invisionzone.com/index.php?showtopic=52445&hl= Are you trying to use the Google custom search? Link to comment Share on other sites More sharing options...
Lucy Posted February 25, 2015 Author Share Posted February 25, 2015 Thanks for the help - got it figured out now. Davej - No, this is just a really simple and not very useful search function I've made for practice. It just searches a given paragraph and tells you how many times the search term was found. I'm also implementing highlighting. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now