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>
Triggering a click synthetically does not cause focus to switch to the element, however the click triggered by hardware does.
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.
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.
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.
I guess you want:
$(".triggerBtn").click(function () {
$(this).closest('div').find('.inputField').focus();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With