I'm dynamically adding buttons to the DOM. On each button, there's a popover. Here's my code:-
<button class="pop-Add" id='button1'>Add</button>
var popOverSettings = {
placement: 'bottom',
container: 'body',
selector: '[rel="popover"]',
html:true,
content: "<button type='button' id='+50' class='btn btn-small pop_button'> + 50 </button>"
}
$('body').popover(popOverSettings);
$('.pop-Add').click(function () {
var id = Math.floor((Math.random() * 1000000) + 1);
button = "<button rel='popover' id='" + id + "'>Click me</button>"
$('body').append(button);
});
jsFiddle
I want to get the id of that ClickMe button whose popover button '+50' is clicked. How can I get it?
This is how I'm currently doing:-
$(document).on('click', '.bid_value_buttons' , function(){
alert($(this).attr('id'))
}
I have done this by using below code:
HTML:
<button class="pop-Add">Add</button>
<script>
function display(el) {
var id = $(el).parent().parent().prev().prop("id");
alert(id);
}
</script>
jQuery Code:
var popOverSettings = {
placement: 'bottom',
container: 'body',
selector: '[rel="popover"]',
html:true,
content: "<button type='button' id='+50' class='btn btn-small btn-empty bid_value_buttons'> + 50 </button>"
}
$('body').popover(popOverSettings);
$('.pop-Add').click(function () {
var id = Math.floor((Math.random() * 1000000) + 1);
button = "<button rel='popover' id='" + id + "' OnClick='display(this);'>Click me</button>"
$('body').append(button);
});
checkout this fiddle.
Please find below the screenshot :
Hope it helps you
Thanks
I think the most simple answer would be to just add the id of the "click me" button as a data-attribute to the newly created popover and accessing that data-attribute:
JS Fiddle
$(document).on('click', '.click-me-button', function(){
var id = $(this).attr('id');
$('.popover-content').last().attr('data-id', id); // Will always be the last popover (newest in DOM)
})
$(document).on('click', '.popover-content' , function(){
alert($(this).attr('data-id'));
});
And if you really need to access the button based off the id, you could just do:
$(document).on('click', '.popover-content' , function(){
var id = $(this).attr('data-id');
alert($('#' + id).attr('id')); // easily access the id
});
Related
I am trying to implement the Bootstrap popover on my HTML page. I have a popup that is in an HTML table which I am building dynamically and I suspect I am not registering the event correctly.
My HTML:
$.each(JSON.parse(data), function (index, elem) {
var radioBtn = "<input type='radio' name='radOption' class='radio selectedOptionAdd' data-value='myData' />";
var popupContent = "TO DO MAKE A TABLE OF DATA";
var popupControl = "<a class='btn btn-lg btn-danger permissionPopUpButton' role='button' data-toggle='popover' data-trigger='focus' title='Dismissible popover' data-content='" + popupContent + "'>Dismissible popover</a>";
myTable += "<tr><td>" + radioBtn + "</td><td>" + popupControl + "</td></tr>";
});
In my document.ready I have the following statement:
// Originally tried this but this doesn't work
//$('[data-toggle="popover"]').popover();
$("body").on("click", ".permissionPopUpButton", function () {
$('[data-toggle="popover"]').popover();
});
Any advice on how to correctly register this event?
I found out that this will work.
$("body").on("click", ".permissionPopUpButton", function () {
$(".popover").css("width", "276px");
$('[data-toggle="popover"]').popover();
});
However I was missing the "tabindex='0'. Once I added that to my tag the popup started working!
var popupControl = "<a tabindex='0' class='btn btn-lg btn-danger permissionPopUpButton' role='button' data-toggle='popover' data-trigger='focus' title='I am a title' data-content='I AM CONTENT HEAR ME ROAR'>Dismissible popover</a>";
I'm adding child elements inside a div using append() and counting/adding a number to each one using ++ to +1 each time an item is added.
I want the value to automatically adjust if an item is removed, for example if I have 4 elements:
Element #1
Element #2
Element #3
Element #4
Currently if element #3 is removed the list looks like this:
Element #1
Element #2
Element #4
But I want it to look like this:
Element #1
Element #2
Element #3
Appreciate any advice on what I should use to achieve this, thanks.
Example code: https://jsfiddle.net/wepsrzkm/
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function () {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
jQuery(".remove_price_rule").click(function() {
jQuery(this).parents('.price_rule_wrapper').remove();
});
});
Decrease price_rule_count by 1 when removing.
After remove one element, alter the existing elements #number.
UPDATED: As from Arun P Johny's answer, we don't need to traverse all the left elements, only need to change those which are after the removed one's text.
The origin code will register multiple events to .remove_price_rule each time you add a item, that means if you create the element 3 times, when you remove one, the logic in the remove handler will execute 3 times, so the price_rule_count will be inconsistent to the actual counts if we use price_rule_count--, however, even if we use jQuery(".price_rule_area_1").children().length; to get real count, its stll redundant to execute the same logic many times.
So It's better to use .on's delegate form here.
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function () {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
});
+jQuery('.price_rule_area_1').on("click", ".remove_price_rule", function() {
// As from Arun P Johny's answer, we only need to change the text after the removed element.
$element = jQuery(this).parents('.price_rule_wrapper');
$element
.nextAll('.price_rule_wrapper')
.find('span')
.text(function(index, prevText) {
return parseInt(prevText, 10) - 1;
});
jQuery(this).parents('.price_rule_wrapper').remove();
--price_rule_count;
// This would be slower as some elements don't need to be traversed.
// jQuery('.price_rule_wrapper').each(function(idx) {
// $(this).find(".price_rule_count > span").text(idx + 1);
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
jsfiddle
Check out this fiddle, I have used CSS counters in order to automatically keep your element number:
https://jsfiddle.net/wepsrzkm/8/
.price_rule_area_1{
counter-reset: section;
}
.price_rule_area_1 .price_rule_wrapper{
counter-increment: section;
}
.price_rule_area_1 .price_rule_wrapper .price_rule_count::after{
content: "#"counter(section);
display:inline-block;
}
You can update the content of the span element inside the price_rule_wrapper element like
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function() {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
});
jQuery('.price_rule_area_1').on('click', ".remove_price_rule", function() {
var $wrapper = jQuery(this).closest('.price_rule_wrapper');
$wrapper.nextAll('.price_rule_wrapper').find('span').text(function(i, text) {
return text - 1
})
$wrapper.remove();
price_rule_count--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
Note: Use event delegation to handler the click event of dynamically recreated elements.
You are binding multiple event handler for each remove element
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
var price_rule_count = jQuery(".price_rule_area_1").children().length;
jQuery('.add_price_rule').click(function() {
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span>' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
});
$('div.price_rule_area_1').on('click', '.remove_price_rule', function() {
// event handler for dynamically generated element
jQuery(this).parents('.price_rule_wrapper')
.nextAll('div')
// get all div after the removing div
.find('span')
// get number span inside it
.html(function(i, v) {
return parseInt(v) - 1;
})
// decrementing value of it
.end().end()
// get back to the removing div
.remove();
// removing the div
price_rule_count--;
// decrementing the count by 1 after removing the element
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
try this mate
<html>
<body>
<div class="price_rule_area_1"></div>
<button class="button-primary add_price_rule" type="button">Add Element</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script>
var price_rule_html = '<button class="remove_price_rule button" type="button">Remove Element</button>';
var price_rule_count = 1;
jQuery('.add_price_rule').click(function () {
var price_rule_count = jQuery(".price_rule_area_1").children().length;
price_rule_count++;
jQuery('.price_rule_area_1').append('<div class="price_rule_wrapper"><div class="price_rule_count">Element #<span class="bull ">' + price_rule_count + '</span></div>' + price_rule_html + '</div>');
jQuery(".remove_price_rule").click(function() {
jQuery(this).parents('.price_rule_wrapper').remove();
price_rule_count--;
alert(jQuery('.price_rule_area_1').children().length)
jQuery('.price_rule_area_1').children().eq(price_rule_count-1).find('.bull').text(price_rule_count)
});
});
</script>
</html>
I have some html in my JS and everything but the button works. The input button appears but when I click it, nothing happens.
function updateFavourite(video) {
document.getElementById("favourite").onclick = function () {
blacklist[video["id"]] = true;
myfavourite.push(video);
var html =
"<input onclick='remove(video);' value='Remove' type='button'></input>" +
"<li class=\"saved\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\{1}\)\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
setVideoF(video);
}
}
Method to call:
function remove (video) {
alert('Favourites removed');
}
It looses its access to video variable, remove the onclick attribute and use jQuery to bind its event, and also use JavaScript Closure to keep the video variable safe:
function updateFavourite(video) {
var clickFunc = (function (video) {
return function () {
blacklist[video["id"]] = true;
myfavourite.push(video);
var html =
"<input class='removeButton' value='Remove' type='button' />" +
"<li class=\"saved\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\{1}\)\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
$("#myfavourite .removeButton").click(function () {
remove(video);
});
};
})(video);
document.getElementById("favourite").onclick = clickFunc;
}
Your code is generating a dynamic html so click event is not registering properly. A little html updated required. Use the "removeVideo"class to your button and use the jquery to
register the click event for dynamic element.
$('body').on('click','.removeVideo', function(){
$(this).val("Clicked");
});
Insted of $('body') you can use the closest(but not dynamic element) parent.
$("#jqxTree-ReportGroups ul").append("<li id=" + [data[i].Id] + " item-checked='true' item-expanded='true' class='treeLi'>
<a class='report-tree-expand' href=''>+</a>
<a class='reportData' id='12345' href=''>" + [data[i].Name] + "</a></li>");
How to get the attribute value of "id" by class name "reportData" when its clicked?
EDIT:
click doesnt work.. If i use Live that function is getting called... How to do get the reportData's Id inside a live function
Take a look at this Code:
$(document).on('click' , '.reportData' , function(){
var idProp= $(this).prop('id'); // or attr()
var idAttr = $(this).attr('id');
console.log('using prop = ' + idProp + ' , using attr = ' + idAttr);
console.log();
return false; // to prevent the default action of the link also prevents bubbling
});
done use live it has been deprecated (on requires jquery version 1.7 and above)
but here is the code using live()
$('.reportData').live('click' , function(){
var idProp= $(this).prop('id'); // or attr()
var idAttr = $(this).attr('id');
console.log('using prop = ' + idProp + ' , using attr = ' + idAttr);
console.log();
return false; // to prevent the default action of the link also prevents bubbling
});
jsfiddle to prove working
http://jsfiddle.net/uvgW4/1/
You can do
$(document).on("click", ".reportDatan", function() {
var id = this.id;
});
Use event delegation since it looks like your adding this dynamically.
Try this:
$('.reportDatan').click(function(){
$(this).attr('id');
});
if you are using jquery 1.9
$('.reportDatan').click(function(){
$(this).prop('id');
});
Your concatenation of HTML String inside jQuery is wrong, take a look at this Code which has live function or if you want this to be readable, you can use JavaScript Template Engine Mustache also
HTML:
<div id="jqxTree-ReportGroups">
<ul>
<li>First</li>
</ul>
</div>
jQuery:
$(document).ready(function () {
var yourLiID = 100;
var aValue = 'Report Data';
var yourLi = "<li id='" + yourLiID + "' item-checked='true' item-expanded='true' class='treeLi'>";
var yourAnchor = "<a class='report-tree-expand' href=''>Your Text</a> ";
var secondAnchor = "<a class='reportData' id='12345' href=''>" + aValue + "</a>";
var yourLiClose = '</li>';
$("#jqxTree-ReportGroups ul").append(yourLi + yourAnchor + secondAnchor + yourLiClose);
$('.reportData').live("click", function(){
var yourAnchorID = $(this).attr('id');
alert('yourAnchorID: ' + yourAnchorID);
return false;
});
});
Refer this jsFiddle Link for demo
<script type="text/javascript">
$("a.route").live('click', function() { // live is better
$("#results").load( $(this).attr('href') );
return false;
});
</script>
That's the code, how can I incorporate the code you just gave me?
The Confirm dialog returns true if the user clicks the OK button, or false if the user clicks on the Cancel button. You can use this value to trigger your script if they've clicked OK like this:
<script type="text/javascript">
$("a.route").live('click', function() {
if (confirm("Are you sure?")) {
$("#results").load( $(this).attr('href') );
}
return false;
});
</script>
if you want to use a custom box you could do it like that:
test link: http://jsfiddle.net/myDry/
function blockmeornot(extlink) {
var oherf = $(extlink).attr('href')
var msgboxID = 'areyousure'
var msgbox = '<div id="' + msgboxID +'"><div><p> put your message here </p><a class="yes" href="' + oherf + '"> yes </a> <a class="no" href="#"> no </a></div></div>'
$('body').append(msgbox)
$('#' + msgboxID + ' a.no').live('click', function(){ $('#' + msgboxID).fadeOut(400, function(){$(this).remove()}) })
}
$('a.external').click(function(){ blockmeornot(this); return false })