Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: trigger click or focus input field

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>
like image 589
user2571510 Avatar asked Dec 17 '13 13:12

user2571510


People also ask

Does click trigger focus?

Triggering a click synthetically does not cause focus to switch to the element, however the click triggered by hardware does.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.

How do you know if input is focused?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.

How do you set focus on input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.


1 Answers

I guess you want:

$(".triggerBtn").click(function () {
    $(this).closest('div').find('.inputField').focus();
});
like image 134
A. Wolff Avatar answered Sep 24 '22 16:09

A. Wolff