10

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>
Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51
user2571510
  • 11,167
  • 39
  • 92
  • 138
  • `$(".triggerBtn").click(function(e){ myFunction(); });` and `$(".inputField").focus(function(e){ myFunction(); });` – TCHdvlp Dec 17 '13 at 13:29

5 Answers5

18

I guess you want:

$(".triggerBtn").click(function () {
    $(this).closest('div').find('.inputField').focus();
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
6

add Onclick="function()" see here if you need to trigger it manually using jquery you can to this by

$("#field1").trigger("click");

see also here

AmOs
  • 129
  • 1
  • 13
1
$(".triggerBtn").on("click",function(e){
      $(this).closest("div").find(".inputField").click();
     //or $(this).closest("div").find(".inputField").focus();
});
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
0
$(".triggerBtn").parent().children("input[type:text]").first().focus()
Jeet
  • 1,350
  • 1
  • 15
  • 32
-1

Updated Jsfiddle: http://jsfiddle.net/ZmL4y/3/

$(document).on("click",".triggerBtn", function() { 
    var inputField =  $(this).closest('div').find('.inputField');
    if($(inputField).is(":visible"))
    {
       $(inputField ).focus();
    }
});
patel.milanb
  • 5,822
  • 15
  • 56
  • 92