Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the focus to the next input in jQuery?

Tags:

jquery

focus

next

I've currently got a script that'll check for the value of a select box, and then enable a text field right next to it, and then hopefully set focus.

I have this at the moment which works fine at enabling the input field...

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true);  }
    else { $(this).next('input').removeAttr("disabled"); }

});

I'm a bit stuck on the 'focus' bit to be honest, I tried "$(this).next('input').focus();" but that didn't focus at all, although it didn't bring up a Javascript error either...

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true); $(this).next('input').focus(); }
    else { $(this).next('input').removeAttr("disabled"); }

});

Any ideas please guys? I'm really stuck on this and it'd be a very simple, but very useful addition to the page I'm building!

Thanks

like image 475
Nick Avatar asked Aug 05 '09 10:08

Nick


People also ask

How do you focus on next input?

To focus on the next field when pressing enter in React, we can set the onKeyDown prop of the inputs to a function that gets the next input and call focus on it. We have the handleEnter function that checks if the pressed key is Enter by checking the event. key property.

How do you focus an element in jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.


1 Answers

Also found a nice little plugin to get the next input: http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select').not(':hidden');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        else {fields.first().focus();}
        return false;
    });
};
like image 106
TimoSolo Avatar answered Nov 04 '22 09:11

TimoSolo