0

I currently have a button in HTML with the following code:

<form id="tfnewsearch" method="get" >
            <input type="text" id="search_query" name="q" size="21" maxlength="120"><input type="button" id="search_button" name="search" value = "Search"onclick="doSearch(this.form.q)">
    </form>

The function 'doSearch()' works only if I click the submit button. What changes do I have to do if it has to work even if I just press the Enter key?

2 Answers 2

7
<form id="tfnewsearch" method="get" onsubmit="doSearch()" >

Simply change the onclick to an onsubmit and attach it to your form!

Sign up to request clarification or add additional context in comments.

4 Comments

but doSearch uses the query as input. Is this exactly what you are referring to ?
<form id="tfnewsearch" method="get" onsubmit="doSearch(this.form.q)"> <input type="text" id="search_query" name="q" size="21" maxlength="120"><input type="button" id="search_button" name="search" value = "Search"> </form>
The function is kind of not at all related to the question. I am using the search string from the search box and generating a URL by appending it to a prefix in the doSearch function.
So, I am able to get the required output only when I specifically click the search button but nothing when I press enter
2

The proper way it to move it to simple JS script

<script type="text/javascript">
    var form = document.querySelector('#tfnewsearch'),
        query = form.querySelector('[name="q"]');

    form.addEventListener('submit', function(){
        doSearch(query.value);      
    });
</script>

7 Comments

how does this fit in the question? I am very new to js. Please bear with me
I've updated code with parameter for the doSearch() function. It's also important to assign stuff like that to any var, because of speed optimization reasons (browser can fastly check for var values, specially in specific scope).
It's better to separate JS logic from HTML attributes. It's the same way like You shouldn't put inline styles="", because it is not good approach to mix semantic structure (html), with presentation layer (css) and logic (JS)
So, do i have to definitely put in this snippet? Can i just not change a few attributes of the button? For example, 'onclick=...' is redirecting the program upon clicking the button. So is there nothing of that sort for clicking the enter key?
How does it fit to question??? Your problem with "no enter support" is because You've used click event for submit button instead of submit event on form element. And moving it to JS is one (or maybe even two or threes step(s) further :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.