11

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>
1
  • $(".triggerBtn").click(function(e){ myFunction(); }); and $(".inputField").focus(function(e){ myFunction(); }); Commented Dec 17, 2013 at 13:29

5 Answers 5

19

I guess you want:

$(".triggerBtn").click(function () {
    $(this).closest('div').find('.inputField').focus();
});
Sign up to request clarification or add additional context in comments.

2 Comments

You guess... Like all of us. As long as this question is unclear, we can't help him/her.
You guessed right ! :) Thanks for the quick reply and sorry I wasnt clear enough.
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

Comments

1
$(".triggerBtn").on("click",function(e){
      $(this).closest("div").find(".inputField").click();
     //or $(this).closest("div").find(".inputField").focus();
});

Comments

0
$(".triggerBtn").parent().children("input[type:text]").first().focus()

1 Comment

shouldn't input[type:text] be input[type='text']?
-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();
    }
});

1 Comment

How can you focus an array of elements ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.