Twitter bootstrap - Focus on textarea inside a modal on click - javascript

Just starting to play around with bootstrap and it's amazing.
I'm trying to figure this out. I have a textarea for feedback inside a modal window. It works great. But I want the focus to go on the textarea when you click on the button to activate the modal. And I can't seem to get it working.
Here is a fiddle: http://jsfiddle.net/denislexic/5JN9A/4/
Here is the code:
<a class="btn testBtn" data-toggle="modal" href="#myModal" >Launch Modal</a>
<div class="modal hide" id="myModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<textarea id="textareaID"></textarea>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>​
Here is the JS
$('.testBtn').on('click',function(){
$('#textareaID').focus();
});​
To resume
When I click on "Launch modal" I want the modal to show up and the focus to go on the textarea.
Thanks for any help.

It doesn't work because when you click the button the modal is not loaded yet. You need to hook the focus to an event, and going to the bootstrap's modals page we see the event shown, that is fired when the modal has been made visible to the user (will wait for css transitions to complete). And that's exactly what we want.
Try this:
$('#myModal').on('shown', function () {
$('#textareaID').focus();
})
​
Here's your fiddle updated: http://jsfiddle.net/5JN9A/5/
Update:
As #MrDBA notes, in Bootstrap 3 the event name is changed to shown.bs.modal. So, for Bootstrap 3 use:
$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
New fiddle for Bootstrap 3: http://jsfiddle.net/WV5e7/

I wanted to have a declarative version of this, so I went with the following :
$(document).ready(function() {
$(".modal").on('shown.bs.modal', function () {
$("[data-modalfocus]", this).focus();
});
});
You can then simply add a data-modalfocus property to your field, like so :
<input type="text" data-modalfocus />
And when the modal pops-up, your field will get focus.

Bootstrap3
$(window.document).on('shown.bs.modal', '.modal', function() {
window.setTimeout(function() {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
Bootstrap 2
$(window.document).on('shown', '.modal', function() {
window.setTimeout(function() {
$('[autofocus]', this).focus();
}.bind(this), 100);
});

You can use the autofocus html element to set the autofocus.
<textarea id="textareaID" autofocus="" ></textarea>
Fiddle here (Click)

If your modal has the 'fade' property:
This will work but you might have to adjust the duration of the timeout and obviously the IDs where needed:
$("#ID-of-modal").on('show', function(event){
window.setTimeout(function(){
$(event.currentTarget).find('input#ID-of-input').first().focus()
}, 0175);
});

I was having major issues in chrome... I hope this helps someone.
//When user clicks link
$('#login-modal-link').on('click',function() {
setTimeout(function(){
//If modal has class
if ($('#login-modal').hasClass('modal')) {
//Whatever input you want to focus in
$('#user_login_modal').focus();
}
},100);
});

As mentioned in one of the comments you need to remove fade from your modal.
So this works for me:
<div id="myModal" class="modal">
...
<textarea class="form-control" rows="5" id="note"></textarea>
</div>
<script>
$('#myModal').on('shown.bs.modal', function () {
$('#note').focus();
})
</script>

I wanted something a bit more generic
$(window.document).on('shown.bs.modal', '.modal', function () {
var timer = window.setTimeout(function () {
$('.firstInput', this).focus();
typeof timer !== 'undefined' && window.clearTimeout(timer);
}.bind(this), 100);
});
With this, I give whatever control I want the CSS class firstInput.
There is a slight delay in setting focus that gives it a certain flair.

I don't know why, but the choosed solution doesn't work for me..
I use the following code snippet instead:
$('#annul-modal').on('show', function() {
setTimeout(function() {$('textarea:first', '#annul-form').focus();}, 400);
});
I know it isn't so pretty but at least it works.. Bootstrap v2.3.0

If you are using bootstrap v3 and you are using both modal dialog and wysihtml5 text editor the following works (assuming #basic is the ID of your modal form):
$('#basic').on('shown.bs.modal', function () {
editor.composer.element.focus()
})

Attaching the event directly to the modal screen didn't work for me. I'm using this code instead:
$('body').on('shown.bs.modal', '.modal', function () {
$('[id$=myField]').focus();
})
With this code I only need to change myField for the id of the control I want to have the focus, it also allows me to define the focus for multiple modal screens, I have something like:
$('body').on('shown.bs.modal', '.modal', function () {
$('[id$=YesCancel]').focus();
$('[id$=YesInverted]').focus();
$('[id$=cancelAddCustomer]').focus();
$('[id$=closeHistoryModal]').focus();
});
Source http://xcellerant.net/2014/08/06/set-focus-on-a-field-when-showing-a-bootstrap-3-modal/

Found doing:
$(document).on('shown.bs.modal', function () {
$(this).find('.form-control:visible:first').focus();
});
Worked well as it just finds the first form-control rather than needing a specific id etc. Be just what is needed most of the time.

Mover para a raiz...
<script>
$(function(){
$("#btnmoverCategoriaRaiz").click(function(){
$("#novoPlaylist").modal();
return false;
});
});
</script>
<div id="novoPlaylist" class= "modal hide">
<div class="modal-header">
<h3>Novo Playlist</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<?echo $form->input("Playlist.nome", array("label"=>"Nome:")) ?>
</form>
</div>
<div class="modal-footer">
Cancelar
Savar
</div>
</div>

Related

use Jquery to click hyperlink

I am trying to create a jquery to click a hyperlink but nothing seems to be working.
HTML
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
no avail
Show all
</div>
what I was trying
$(".warning a").click()
Any suggestions?
Note that jQuery-initiated "click" events will fire the event but will not cause navigation to occur.
Instead you can read the link's HREF attribute and directly set the window location:
// The click event:
$('a').on("click", function() {
console.log("Click event fired");
})
var demo1 = function() {
// This will trigger the click event, but will not navigate.
$(".warning a").click()
}
var demo2 = function() {
// This will navigate but will not trigger the click event. (If you need both to happen, trigger the click event first, and consider delaying the window location update if necessary.)
var url = $(".warning a").attr("href")
window.location = url;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
Show all
</div>
</div>
</main>
<!-- for demo: -->
<button onclick="demo1()">Won't work</button>
<button onclick="demo2()">Will work</button>
jQuery's .click() (without arguments) is a shortcut for .trigger("click"):
function(a,c) {
return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b)
}
Therefore, it will not actually click the element, but just call the click event handlers attached to it, as you can see here:
const $link = $("a");
$link.on("click", () => {
console.log("Clicked? Not really...");
});
$link.click();
$link.trigger("click");
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to get a reference to the actual DOM element and then call HTMLElement.click() on that:
$("a")[0].click();
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can user the vanilla click method:
document.querySelector('.warning > a').click()
// equivalent jquery
//$('.warning > a')[0].click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="warning" role="alert">
no avail
Show all
</div>
Whenever you select div class with hyperlink there you get array because you can have multiple hyperlinks so you need to add somthing like below
Code
$('.warning a')[0].click();
For reference link
Get working example for click event
If I need to redirect, I typically use window.location.href
window.location.href=$(".warning a").attr('href');

Fire button click event when there are multiple classes on an element

How would I fire a button click event when a particular button is pressed (in this case the accept button).
I've tried the following but with little success:
Javascript
$('.notification-expand .Request .active-item > .accept-button').click(function () {
alert("hello");
});
HTML
<div class="notification-expand Request active-item" style="display: block;">
<div class="notification-body"></div>
<br>
<p>
<button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
</p>
<div class="row">
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
</div>
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
</div>
</div>
</div>
Fiddle here
You have error in your selector , it should look like this:
$('.notification-expand.Request.active-item .accept-button').click(function () {
alert("hello");
});
You need to concatenate all classes without spaces to catch your target button
$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
alert("hello");
});
See the updated snippet
Notice the syntax of ".className1.className2" instead of ".className1 .className2"
should be something like:
$('button.accept-button').click(function(){ ... });
there is really no need to go down the whole list if this is the whole code
----edit----
so when there are more items but only 1 active(i guess) then just target the active-item class:
$('div.active-item button.accept-button').click(function(){ ... });
try
$('.accept-button', $('.notification-expand.active-item')).click(function () {
alert("hello");
});
or
$('.notification-expand.active-item')).find('.accept-button').click(function () {
alert("hello");
});
Just give the button an id and reference back to that.
HTML
<button id="btnSubmitData"> Ok Button </button>
JQuery Code
$('#btnSubmitData').click(function(){ ... });
You can also have multiple button Ids bind to the same event:
$('#btnAccept, #btnReject, #btnWarning').click(function () {
alert("hello");
});
Take a look at the updated Working Fiddle.

Add a button that closes the popup with popup.js

I'm having troubles creating an exit button for the following script.
I'm using popup.js from http://docs.toddish.co.uk/popup/.
It sais that in order to do it we should use popup.close() from inside the object. But there are no examples and I can't get it to work. Does anyone have an idea?
JSFiddle link = http://jsfiddle.net/andrewallen817/bedhhu1o/3/
Html:
<a href=#txt class="popup" >Click here</a>
<div id="txt" style="display:none">
<h1>This is a title</h1>
<p>this is some text</p>
<button>close</button>
</div>
JS
$(function(){
$('.popup').popup();
});
I fixed it for you by looking at the doc. JSfiddle
$(function () {
$('.popup').popup({
afterOpen: function () {
var popup = this;
$('button').click(function () {
popup.close();
});
}
});
});
You might want to specify which button you want to give the popup.close() or else every button will have it.

How to reset the bootstrap modal when it gets closed and open it fresh again?

I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.
How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.
<!-- Modal -->
<div
class="modal fade"
id="myModal"
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">Select Language</h4>
</div>
<div class="modal-body">
<button type="button" class="btn" data-dismiss="modal">Close</button>
<button type="button" class="btn" id="submit_form">Submit</button>
<div class="modal-body1">
<div id="placeholder-div1"></div>
</div>
</div>
<div class="modal-footer">
<script>
$("#submit_form").on("click", function () {
$(".modal-body1").html("<h3>test</h3>");
});
</script>
<script>
$(function () {
$(".modal-footer").click(function () {
$(".modal").modal("hide");
});
});
</script>
</div>
</div>
</div>
</div>
-- Update ---
Why doesn't this work?
<script type="text/javascript">
$(function () {
$("#myModal").on("hidden.bs.modal", function (e) {
console.log("Modal hidden");
$("#placeholder-div1").html("");
});
});
</script>
Just reset any content manually when modal is hidden:
$(".modal").on("hidden.bs.modal", function(){
$(".modal-body1").html("");
});
There is more events. More about them here
$(document).ready(function() {
$(".modal").on("hidden.bs.modal", function() {
$(".modal-body1").html("Where did he go?!?!?!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch modal
</button>
<div class="modal fade" id="myModal" 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">Modal title</h4>
</div>
<div class="modal-body">
<div class='modal-body1'>
<h3>Close and open, I will be gone!</h3>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Tried it and working well
$('#MyModal').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
})
reset is dom build-in funtion, you can also use $(this).find('form')[0].reset();
And Bootstrap's modal class exposes a few events for hooking into modal functionality, detail at here.
hide.bs.modal This event is fired immediately when the hide instance
method has been called.
hidden.bs.modal This event is fired when the modal has finished being
hidden from the user (will wait for CSS transitions to complete).
What helped for me, was to put the following line in the ready function:
$(document).ready(function()
{
..
...
// codes works on all bootstrap modal windows in application
$('.modal').on('hidden.bs.modal', function(e)
{
$(this).removeData();
}) ;
...
..
});
When a modal window is closed and opened again, the previous entered and selected values, will be reset to the initial values.
I hope this will help you as well!
Try cloning, then removing and re-adding the element when the modal is hidden. This should keep all events, though I haven't thoroughly tested this with all versions of everything.
var originalModal = $('#myModal').clone();
$(document).on('#myModal', 'hidden.bs.modal', function () {
$('#myModal').remove();
var myClone = originalModal.clone();
$('body').append(myClone);
});
To reset all the input fields in a modal use the following.
$(".modal-body input").val("")
Here's an alternative solution.
If you're doing a lot of changes to the DOM (add/removing elements and classes), there could be several things that need to be "reset." Rather than clearing each element when the modal closes, you could reset the entire modal everytime it's reopened.
Sample code:
(function(){
var template = null
$('.modal').on('show.bs.modal', function (event) {
if (template == null) {
template = $(this).html()
} else {
$(this).html(template)
}
// other initialization here, if you want to
})
})()
You can still write your initial state in HTML without worrying too much about what will happen to it later. You can write your UI JS code without worrying about having to clean up later. Each time the modal is relaunched it will be reset to the exact same state it was in the first time.
Edit: Here's a version that should handle multiple modals (I haven't tested it)...
(function(){
$('.modal').on('show.bs.modal', function (event) {
if (!$(this).data('template')) {
$(this).data('template', $(this).html())
} else {
$(this).html($this.data('template'))
}
// other initialization here, if you want to
})
})()
(function(){
$(".modal").on("hidden.bs.modal", function(){
$(this).removeData();
});
});
This is perfect solution to remove contact while hide/close bootstrap modal.
That's works for me accurately
let template = null;
$('.modal').on('show.bs.modal', function(event) {
template = $(this).html();
});
$('.modal').on('hidden.bs.modal', function(e) {
$(this).html(template);
});
also, you can clone your modal before open ;)
$('#myModal')
.clone()
.modal()
.on('hidden.bs.modal', function(e) {
$(this).remove();
});
Reset form elements ( Works with bootstrap 5 as well). Sample code :
$(document).on("hidden.bs.modal", "#modalid", function () {
$(this).find('#form')[0].reset();
});
you can try this
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It will remove all the data from the model and reset it.
I am using BS 3.3.7 and i have a problem when i open a modal then close it, the modal contents keep on the client side no html("") no clear at all. So i used this to remove completely the code inside the modal div.
Well, you may ask why the padding-right code, in chrome for windows when open a modal from another modal and close this second modal the stays with a 17px padding right.
Hope it helps...
$(document)
.on('shown.bs.modal', '.modal', function () {
$(document.body).addClass('modal-open')
})
.on('hidden.bs.modal', '.modal', function () {
$(document.body).removeClass('modal-open')
$(document.body).css("padding-right", "0px");
$(this).removeData('bs.modal').find(".modal-dialog").empty();
})
Sample code:
$(document).on('hide.bs.modal', '#basicModal', function (e) {
$('#basicModal').empty();
});
The below statements show how to open/reopen Modal without using bootstrap.
Add two classes in css
And then use the below jQuery to reopen the modal if it is closed.
.hide_block
{
display:none !important;
}
.display_block
{
display:block !important;
}
$("#Modal").removeClass('hide_block');
$("#Modal").addClass('display_block');
$("Modal").show("slow");
It worked fine for me :)
Using BS 3.3.7
$("#yourModal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null); // will clear all element inside modal
});
/* this will change the HTML content with the new HTML that you want to update in your modal without too many resets... */
var = ""; //HTML to be changed
$(".classbuttonClicked").click(function() {
$('#ModalDivToChange').html(var);
$('#myModal').modal('show');
});
Reset form inside the modal. Sample Code:
$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
$('#myModal form')[0].reset();
});
To reset/clear all input fields from bootstrap modal use the following code:
$(".modal-body input").val("")
To hide/close bootstrap modal use the following code:
$('#yourModalId').modal('hide');
Keep Coding 😎

How can I render a form after a button is clicked in Colorbox?

I'm trying implement a button inside a Colorbox that will update the modal and render a form.
An example of this is Pinterest's add functionality. "Homepage > Add a Pin > Pin URL"
I've tried copying Colorbox's inline HTML example.
<script type="text/javascript">
$(document).ready(function () {
$(".inline").colorbox({inline:true, width:"50%"});
$('a[rel="colorbox"]').live("click", function() {
$.colorbox({
open: true,
href: this.href
});
return false;
});
});
</script>
<div style='display:none'>
<div id='inline_content' style='padding:10px; background:#fff;'>
<p><strong>Add a Promotion</strong></p>
<p><a id="click" href="#" style='padding:5px; background:#ccc;'>Click me, it will be preserved!</a></p>
<p><strong>If you try to open a new ColorBox while it is already open, it will update itself with the new content.</strong></p>
<p>Updating Content Example:<br />
<a class="ajax" href="**shared/promotion_form**" rel="colorbox">Add a Promotion</a></p>
</div>
</div>
The problem is that the form is _promotion_form.html.erb so I can't link to it.
Try moving your selector up a level, and updating to jQuery 1.7.1
Maybe something like this:
$('body').on("click", "a[rel="colorbox"]", function() {
So this way you're watching the body for any element that has that selector "a[rel='colorbox']".
Hope this helps.

Categories