jQuery: trigger click or focus input field

user2571510 picture user2571510 · Dec 17, 2013 · Viewed 95.3k times · Source

I have a page with multiple divs that all look like the example below. Each div contains a field, a hidden field and a button.

How can I achieve that by click on the button the (visible) input field gets triggered ? I need to trigger either a click or focus as both fire the same function.

Each button in question has the class="triggerBtn" and the corresponding input field has the class="inputField".

Example div:

<div>
    <input type="text" class="inputField" id="field1" name="field1" />
    <input type="hidden" name="field1" />
    <button type="button" class="btn btn-primary triggerBtn">Find</button>
</div>

Answer

A. Wolff picture A. Wolff · Dec 17, 2013

I guess you want:

$(".triggerBtn").click(function () {
    $(this).closest('div').find('.inputField').focus();
});