Sarah
Sarah

Reputation: 302

how to focus a button when a textbox is clicked

I have a textbox that when a user clicks inside it,it should put a focus on a button.I dont need to use an enter key press.i just want to focus on a button when a user clicks inside of a textbox.

$("#txtBox").click(function() {

  alert("The textbox is clicked."); //added for testing purposes it doesnt get hit.
  $("#button").focus();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-2">
  <label for="txtBox" class="sr-only">Text</label>
  <input type="text" class="form-control" id="txtBox" name="txtBox"></div>
<div class="form-group col-sm-1">
  <label for="button" class="sr-only">submit</label>
  <button type="button" class="btn btn-default" id="button" name="button">Focus Me</button></div>

the problem is that my html is stored in a SQL script.so its not detecting txtBox

Upvotes: 3

Views: 1974

Answers (1)

Pedram
Pedram

Reputation: 16575

So, according to comments, you load html via ajax, you append html after DOM so you need to use live (bind) function, you can use .on like this:

$("#txtBox").on('click',function() {

  alert("The textbox is clicked."); //added for testing purposes it doesnt get hit.
  $("#button").focus();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-2">
  <label for="txtBox" class="sr-only">Text</label>
  <input type="text" class="form-control" id="txtBox" name="txtBox"></div>
<div class="form-group col-sm-1">
  <label for="button" class="sr-only">submit</label>
  <button type="button" class="btn btn-default" id="button" name="button">Focus Me</button></div>

Or

$(document).on('click','#txtBox',function() {

  alert("The textbox is clicked."); //added for testing purposes it doesnt get hit.
  $("#button").focus();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-2">
  <label for="txtBox" class="sr-only">Text</label>
  <input type="text" class="form-control" id="txtBox" name="txtBox"></div>
<div class="form-group col-sm-1">
  <label for="button" class="sr-only">submit</label>
  <button type="button" class="btn btn-default" id="button" name="button">Focus Me</button></div>

Upvotes: 1

Related Questions