mythicalprogrammer
mythicalprogrammer

Reputation: 4737

IE9, focus on input text box, but pressing enter will execute the first input button. I need it to stop

I have a web app, where people can search for stuff. In IE9 the focus is on the search input element but the first button is highlighted so when someone press enter it would always execute the first button.

I don't want people to be able to press enter and execute the first button.

The reason is because some people tends to press enter after typing in the search's input text box even though it's base on keyup event.

I've try refocusing it to the search input element. I've also try blurring the button. It doesn't seem to work.

Does anyone know a solution to this?

Thank you for your time.

edit: I don't want to highjack the enter button because what if someone actually tab the focus on to the first button and press enter? Maybe I can check for that? Or maybe there's a better solution?

Edit 2: Found a similar problem here: Stopping IE from highlighting the first submit-button in a form But the solution is for that question is ASP.

edit 3:

A code example:

    <div >
        <label>ETTRN:<input type="text" id="search" maxlength="16" /></label>
        <input type="submit" value="Generate CSV" id="generate_csv" />
    </div>

Upvotes: 2

Views: 5707

Answers (3)

PuiMan Cheui
PuiMan Cheui

Reputation: 104

The problem is similar to what a document has described here: https://github.com/aleen42/PersonalWiki/issues/32#issuecomment-489966824

If you want to solve the problem, you can use keypress or keydown event instead:

$('input.input-wrapper').on('keydown', e => { console.log(e.keyCode); });

Or wrap the input element with a empty form:

<form action="javascript: void(0);">
    <input type="text" class="input-wrapper" value="" />
</form>
<button>test</button>

Upvotes: 0

mythicalprogrammer
mythicalprogrammer

Reputation: 4737

I figure out a solution.

jQuery('*:focus').live('keydown', function(event) {
    if (event.keyCode == 13) {
        switch(jQuery(this).attr('id')) {
            case 'search' :
            case 'date-start':
            case 'date-end':
                event.preventDefault();
                return false;
        }
    }
});

I only care about when the focus is on the text input elements, that are used for searching (namely search, date-start, and date-end). So if one these three text input elements is in focus while a key is press, check if it's the Enter key (13), if it is then disable the default.

Thank you all for helping.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Put the search box inside a <form> all on its own.

<form action="javascript:void(null);" method="post">
    <input type="text" id="searchbox" />
</form>

This will (or at least, should) prevent IE (or any browser) from treating the first button as the action for the Enter key.

Upvotes: 4

Related Questions