Next Closest submit

http://stackoverflow.com/questions/32799675/next-closest-element-jquery

by Taleeb Anwar

HTML

<div><a class="button">Button</a>
</div>
<input type="submit" value='1' />
<a class="button">Button</a>

<div>
    <!-- The input there can be into an another `div`, etc .. -->
    <input type="submit" value='2' />
</div>

JavaScript

$('.button').click(function () {
    var button = findButton($(this));
    console.log($(button).val());
});

function findButton(ctrl, skipChildren) {
    var controlToReturn = null;
    if ($(ctrl).prop('type') === 'submit') {
        controlToReturn = $(ctrl);
    } else {
        if(!skipChildren){
            $(ctrl).children().each(function () {
                controlToReturn = findButton($(this));
                if (controlToReturn != null) {
                    return false; //break
                }
            });
        }

        if (controlToReturn === null || controlToReturn === undefined) {
            $(ctrl).nextAll().each(function () {
                controlToReturn = findButton($(this));
                if (controlToReturn != null) {
                    return false; //break
                }
            });
        }

        if (controlToReturn === null || controlToReturn === undefined) {
            $(ctrl).parents().each(function(){
                
                controlToReturn = findButton($(this), true);
                if (controlToReturn != null) {
                    return false; //break
                }
            });
        }
    }

    return controlToReturn;
}