Jquery click function not working for the button inside popover - javascript

I am trying to alert an message when clicked on button with id tagit. but the whole form is appearing in the bootstrap popover. i also added the jquery for alerting message,but its not showing any alert dialog boxes,but when i call the same thing in javascript it is showing the alert. but i need it to be in jquery. how can i do this?
var htmlcont ='<table class="pop-table"><tr><td><button class="btn btn-warning" id="tagit">FILTER</button></td></tr></table>';
$('[data-toggle="popover"]').popover({content: htmlcont, html: true});
$("#tagit").click(function(){
alert("hello this is working");
});

You need to use event delegation, like so
$(document).on('click', "#tagit", function() {
console.log("hello this is working");
});

Event delegation for dynamic created DOM elements. Try to use Immediate parent selector to traverse easily and quickly
$(document).on('click', '#tagit', function() {
}):

Related

How to get the current/this object on button click using bind event?

I have following code:
$(document).bind('click', '.btn-yes .btn-no', function() {
$(this).toggleClass("btn-warning");
alert("test"); // <-- this works...
});
.btn-yes and .btn-no are two classes which are attached to buttons. When they are clicked, I want the btn-warning class to get attached to that button, but this is not working...
Can anyone let me know what I am doing wrong?
You need to have a comma , between your selector:
'.btn-yes, .btn-no'
and you should use event delegation only if your elements are dynamically generated after page load.
If such a case then the preferred method is .on() as per latest jQuery library. You can see this in action in the snippet below.
$(document).on('click', '.btn-yes, .btn-no', function() {
$(this).toggleClass('btn-warning');
});
.btn-warning{background:red; color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-yes'>Yes</button><button class='btn-no'>No</button>
Problem:
When you don't use comma , in your selector such as in this case you are actually trying to bind a click event on the child .btn-no which has the parent .btn-yes.
Try this:
$(document).bind('click','.btn-yes .btn-no',function(e){
$(e.target).toggleClass("btn-warning");
});
'.btn-yes .btn-no' denotes to the btn-no inside btn-yes not separate elements. So, separate your elements with a comma and use click event for that.
I also recommend you to use on instead of bind method:
$(document).on('click', '.btn-yes, .btn-no', function(){
$(this).toggleClass("btn-warning");
});
If you have jquery version 1.7+ use on method
$(document).on('click', '.btn-yes,.btn-no', function() {
$(this).toggleClass("btn-warning");
});

Button click event based on class isn't being fired on button that is dynamically created.

I have a table with dynamically created rows. Each row has a link button that you click on to delete that row. This is the click function here:
$(".deleteButton").on('click', function(){
console.log("Delete Hit");
var successful = deleteEntry($(this).attr('id'));
if(successful == true){
$(this).parent().parent().remove();
}else{
alert("Delete Unsuccessful.");
}
});
Some of the buttons are created with one function when the page first loads. Those work, but this other function seems to create a button with the right classes for the event to fire. It creates a link like this.
<a class="deleteButton dButton" href="#">
while the one that works right creates a link like this,
<a href='#' class='deleteButton'>
I have checked in the inspector and it says that the button has the class deleteButton, which is required to fire the event, but it seems to be ignoring it entirely. The Delete Hit never shows in the console.This has really confused me for some time, and I'd appreciate the help anyone can give.
You need to use delegated events for elements that doesn't exist on DOM when you bind event handler
$(document).on('click', '.deleteButton', function(){...}
Where document can be any .deleteButton container that exists at handler bind time.
You can delegate your events.
$(document).on('click', '.deleteButton', function(e){
//do something
});
here is a similar post where I explain the differences between bind live and "on".
How Jquery/Javascript behave on dynamic content updation?
The existing buttons get their event handlers on page load, but the new button is added to the DOM afterwards. You would have to update your JavaScript code, like this:
$(document).on('click', '.deleteButton', function(){
console.log("Delete Hit");
var successful = deleteEntry($(this).attr('id'));
if(successful == true){
$(this).parent().parent().remove();
}else{
alert("Delete Unsuccessful.");
}
});
Find more info in the jQuery docs at http://api.jquery.com/on/#direct-and-delegated-events.

Jquery appending with styling and functions

i appending buttons with some IDs and i use those IDs to make on click stuff
when it appending didn't take button() effect
and on click it don't take the function that I created it for this button id
$("button#edit-doc").each(function() {
$(this).button();
$(this).on("click", function(){
alert("clicked");
});
});
append button
$("#append").on("click", function(){
$('div#container').append("<button id='edit-doc'> Edit </button>");
});
container
<div id="container"></div>
This seems to be what you're after:
function handler() { alert('clicked'); }
$("#append").on("click", appendButton);
function appendButton(){
$('#container').append(function() {
return $("<button id='edit-doc'> Edit </button>").on("click", handler);
})
}
http://jsfiddle.net/PF8xY/
See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.
$(document).on("click", "#selector", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.
Something like:
// Load all buttons with class=edit-doc and add event listner
$(function() {
$("button.edit-doc").button().on("click", function(){
alert("clicked");
});
});
// Append button if button with id=append is clicked
$("#append").on("click", function(){
var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
$('div#container').append(button);
$(button).button().on("click", function(){
alert("clicked");
});
});
Working example:
http://jsfiddle.net/RC9Vg/

Prevent icon inside disabled button from triggering click?

Trying to figure out proper way to make a click event not fire on the icon of a disabled link. The problem is when you click the Icon, it triggers the click event. I need the selector to include child objects(I think) so that clicking them triggers the event whenever the link is enabled, but it needs to exclude the children when the parent is disabled.
Links get disabled attribute set dynamically AFTER page load. That's why I'm using .on
Demo here:(New link, forgot to set link to disabled)
http://jsfiddle.net/f5Ytj/9/
<div class="container">
<div class="hero-unit">
<h1>Bootstrap jsFiddle Skeleton</h1>
<p>Fork this fiddle to test your Bootstrap stuff.</p>
<p>
<a class="btn" disabled>
<i class="icon-file"></i>
Test
</a>
</p>
</div>
</diV>​
$('.btn').on('click', ':not([disabled])', function () { alert("test"); });​
Update:
I feel like I'm not using .on right, because it doesn't take the $('.btn') into account, only searching child events. So I find myself doing things like $('someParentElement').on or $('body').on, one being more difficult to maintain because it assumes the elements appear in a certain context(someone moves the link and now the javascript breaks) and the second method I think is inefficient.
Here is a second example that works properly in both enabled/disabled scenarios, but I feel like having to first select the parent element is really bad, because the event will break if someone rearranges the page layout:
http://jsfiddle.net/f5Ytj/32/
Don't use event delegation if you only want to listen for clicks on the .btn element itself:
$('.btn').on('click', function() {
if (!this.hasAttribute("disabled"))
alert("test");
});​
If you'd use event delegation, the button would need to be the matching element:
$(someParent).on('click', '.btn:not([disabled])', function(e) {
alert('test!!');
});​
Demo
Or use a true button, which can really be disabled:
<button class="btn" [disabled]><span class="file-icon" /> Test</button>
Demo, disabled.
Here, no click event will fire at all when disabled, because it's a proper form element instead of a simple anchor. Just use
$('.btn').on('click', function() {
if (!this.disabled) // check actually not needed
this.diabled = true;
var that = this;
// async action:
setTimeout(function() {
that.disabled = false;
}, 1000);
});​
.on('click', ':not([disabled])'
^ This means that, since the icon is a child of the button ".btn", and it is not disabled, the function will execute.
Either disable the icon, also, or apply the event listener only to the <a> tag that is your button, or use e.stopPropagation();
I would suggest using e.stopPropagation();, this should prevent the icon from responding to the click.
That doesn't seem to work for me ^
Disabling the icon, however, does.
I would prefer to add the event using delegation here as you are trying to base the event based on the attributes of the element.
You can add a check condition to see if you want to run the code or not.
$('.container').on('click', '.btn', function() {
if( $(this).attr('disabled') !== 'disabled'){
alert('test!!');
}
});​
Check Fiddle
You're not using the selector properly.
$('.btn').not('[disabled]').on('click', function () {
alert("test");
});​
See it live here.
Edit:
$('.container').on('click', '.btn:not([disabled])', function () {
alert("test");
});​
I think what you need is:
e.stopPropagation();
See: http://api.jquery.com/event.stopPropagation/
Basically something like the following should work
$('.icon-file').on('click', function(event){event.stopPropagation();});
You may want to add some logic to only stop bubbling the event when the button ist disabled.
Update:
not sure, but this selector should work:
$('.btn:disabled .icon-file')

why jquery detach element will cause a form to submit?

i wonder why in the following example, trying to detach an element (li) causes the form containing it to submit
html
<form id="frmToDo" name="frmToDo">
<p id="lineInput">
...
<input type="submit" id="btnSubmit" value="Add" />
</p>
<ul id="todolist">
<!-- added in ajax -->
</ul>
</form>
JS
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
I guess you just want to remove the li element in which the button was clicked.
So instead of using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
Try using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$(this).parent().detach();
return false;
});
That's not a button, it's an input element.
$("#todolist").delegate("li[id^=task-] input:submit", "click", function() {
I am not sure if this is the cause of your problem but you are not using the detach function correctly if your intention is to detach an li element. The argument of the detach function is a selector expression that filters the set of matched element in the jQuery element that you are calling the function on. In your code you call detach on $('#todolist'), which means you want to detach the todolist element, if it matches the argument passed.
You should do something like this instead :
$('#todolist li').detach(); //this will detach all the li elements
I am not sure if this can explain the fact that your form is submitting. If it is not : what event triggers the submit event of your form ? Maybe you use a button or input element that is placed inside the form and triggers the submit of the form ?
Unless there's some relevant code missing, you seem to assign a handler to the onclick event outside a $(document).ready() block. That makes it possible to run the assignment before the #todolist is loaded, thus failing to find the buttons and attach handlers.
With no event cancelling, the default behaviur for a button is to submit the form.
Try this:
$(document).ready(function(){
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
});

Categories

Resources