Setting the focus to the next input in jQuery?

后端 未结 3 847
日久生厌
日久生厌 2021-01-05 07:22

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 a

相关标签:
3条回答
  • 2021-01-05 08:06

    Modified of the above answer with cached this jq object. Also the filter inside next is not needed. next() will only ever return the next sibling. The filter is basically saying get me the next only if it is an input or whatever filter you give. If you are sure the next is the desired object there is no need to include the filter.

    $("#assessed select").change(function () {
        var $this = $(this);
        if( $this.val() === 'null') {
            $this.next()
                 .attr("disabled", true);
        }
        else {
            $this.next()
                 .removeAttr("disabled")
                 .focus();
        }
    });
    
    0 讨论(0)
  • 2021-01-05 08:15

    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;
        });
    };
    
    0 讨论(0)
  • 2021-01-05 08:18

    I think that your problem might be that it's not possible to set the focus to a disabled input control (at least in some browsers/operating systems).

    Your focus() call is basically in the wrong block - it should be in the else block, not the if block.

    Like this:

    $("#assessed select").change(function () {
    
        if($(this).val() == 'null') { $(this).next('input').attr("disabled", true); }
        else { $(this).next('input').removeAttr("disabled"); $(this).next('input').focus(); }
    });
    
    0 讨论(0)
提交回复
热议问题