Add css: focus selector via jQuery

I have a Bootstrap mod with a form that fires when two buttons on a page are clicked.

When one specific button is clicked, I want a specific input field inside the form to have focus, like the cursor in that field, and the style is applied for: focus.

$('.bio-input').focus();

doesn't seem to work (although it does work in the code snippet). Even though this element that I am trying to bring into focus is in modal mode, the modal appears as partial on page load, so the element is available in the DOM on click.

At the bottom of my view (slim), I have a partial that contains a modal:

 = render partial: 'users/profile/edit_profile_modal'

      

The modal has an identifier #popup-editprofile

.

Then below, my button tag has this id as the data target and the data toggle is "modal".

Thanks in advance for your help.

$(document).ready(function() {
  $('.edit-bio-btn').click(function() {
    $("#bio-input").focus();
  })
});
      

#bio-input:focus {
  border-left: 5px solid orange;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button name="button" type="submit" class="button btn btn-xs edit-bio-btn" data-target="#popup-editprofile" data-toggle="modal"><i class="fa fa-pencil"></i><span>Edit bio</span></button>

<textarea name="profile[bio]" id="bio-input" placeholder="Enter Bio" class="form-control edit-profile-input"></textarea>
      

Run codeHide result


+3


source to share


3 answers


Boot modal events: http://getbootstrap.com/javascript/#modals-events

After finally providing the information that you are using the bootstrap modem, the answer becomes clear:

$('#id-of-modal-element').on('shown.bs.modal',function() {
  $('.bio-input',this).focus();
});

      



This snippet says when your modal fires an event shown.bs.modal

, focus on the element .bio-input

that is inside that modal.

If that doesn't work for you, you need to provide a link to your page or code that reproduces your problem.

+2


source


You can use the function focus()

. After pressing the button, the input field will be focused.

$('.edit-bio-btn').click(function() {
    $('input.thisClass').focus();
})

      



DEMO

+3


source


Try this: http://jsfiddle.net/mgm1k5s7/

$("#button").on("click", function () {
    $("#input").focus();
});

      

+2


source







All Articles