Call a JavaScript function by hitting enter in a textbox without global events of jQuery

Paragon picture Paragon · Apr 5, 2011 · Viewed 13.9k times · Source

I am working on a project with the goal of learning, and I am avoiding jQuery thus far to learn as much JavaScript as possible. I have been successfully using onkeypress to determine whether or not enter was hit in a textbox or textarea, but after adding a searchbar on me website, I discovered that events like onkeypress are global (ie. hitting enter in the search bar activates my 'send message' textarea).

I am also using AJAX, and thus I do not want a simple form submit. I am also hoping to use a textarea, since I am after multiple lines (so that more text is visible).

Under these constraints, is this reasonable to do without using jQuery? If so, how can I do it? Other answers on the site simply point to jQuery.

Thanks,

Paragon

Edit: I was asked for code, so here is the relevant HTML and JavaScript. Here is one of the inputs:

<input type="text" id="search" name="search" onkeypress="return activate(event, this.value);"/>

Here is the javascript to go along with it:

function activate(e, message)
{   
    if (isNotEnter(e))
    {   
        return true;
    }   
    else // ie. enter was pressed
    {   
        // only proceed to search() if message is not empty
        if (message.length >= 1)
        {   
            search();
        }   
        return false;
    }   
}

And the function isNotEnter():

function isNotEnter(e)
{   
    if (e.keyCode == 13) 
    {   
        return false;
    }   
    else
    {   
        return true;
    }   
}

Answer

Porco picture Porco · Apr 5, 2011

You should use jquery because it is awesome, easy to learn, gets rid of browser issues, etc.

If you are totally against it though, it can be done with pure JS. It would help if you show your code, but you are probably binding the onkeypress event to the document when you should be binding it to the input.

$("#search").keypress(function()
{
//do function here, use this to refer to the element
});