javascript - Focus on a textarea after custom text on a bootstrap floating modal form -
javascript - Focus on a textarea after custom text on a bootstrap floating modal form -
i using bootstrap invoke simple modal form contains textarea field , couple of buttons. setting custom text (variable length) in textarea while invoking modal form. want focus on textarea field after custom text user can start typing after that. have mentioned implemenation of below. can tell how accomplish this?
here fiddle: http://jsfiddle.net/jlymtdg8/
a bit explanation here -
here modal (all bootstrap stuff)-
<div class="modal fade" id="msg" tabindex="-1" role="dialog" aria-labelledby="mymodallabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">close</span></button> <h4 class="modal-title" id="mymodallabel">type message</h4> </div> <div class="modal-body"> <textarea id="message" class="form-control"></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">cancel</button> <button id="postmodalbutton" class="btn btn-primary btn-sm">post</button> </div> </div> </div>
and here how gets invoked -
<div class="pull-right"> <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#msg" data-screenname="type after this"> post message </button> </div>
this how prefilling textarea , setting focus, setting cursor on first line rather after screen_name -
$(this).on('shown.bs.modal', '#msg', setfieldandfocus) var setfieldandfocus = function () { var screen_name = $("button[data-target='#msg']").data("screenname"); $("#message").val(screen_name + " "); $("#message").focus(); };
sam can seek next javascript code:-
var screen_name = '', old_message = '', new_message = ''; $("#msg").on('shown', function() { screen_name = $("button[data-target='#msg']").data("screenname"), old_message = $.trim($('#message').val()), new_message = ( old_message.length == 0 ) ? screen_name : old_message; $("#message").focus().val(new_message + " "); });
let me explain why have used code. js fiddle link have provided understand using bootstrap 2 version, code using
$("#msg").on('shown.bs.modal', function(){ ... }
was introduced in bootstrap 3. have changed to
$("#msg").on('shown', function(){ ... }
and line
$("#message").focus().val(new_message + " ");
is used can set focus after custom text.i hope resolve issue.
javascript jquery twitter-bootstrap twitter-bootstrap-3
Comments
Post a Comment