I have a script containing $('a').on('click', function () {alert($(this).attr('class')); });
In my contextmenu function, I create a list with links
$(function () {
$('a').on('contextmenu', function (event) {
$("<ul id='menu'></ul>")
.append('<li>Test 1</li>')
.append('<li>Test 2</li>')
.appendTo("body")
.css({ top: event.pageY + "px", left: event.pageX + "px" });
return false;
});
});
However, the first piece of code (the on click event) does not fire when the link in the list is clicked. However, it fires for every other link on the page. How can I fix this so that my script works on dynamic elements
Just a rehash of another SO question.
Calling the jQuery on method on $(document) and providing the 'selector' option will bind the callback to dynamically added elements matching the selector parameter.
That is, this:
$(document).on('click', 'a', function () {
alert( $(this).attr('class') );
});
instead of this:
$('a').on('click', function () {
alert($(this).attr('class'));
});
Related
I am trying to make a progress bar the progress bar works fine but its not changing text within html and keeps static 0%. N.B I am pasting here only relevant codes to avoid a large page of code.
<div class="progressTopBar"><div class="inner-progressBar" :style="{width: this.ProgressBar }">
#{{ getProgressBar() }}
</div></div>
//property
data: function () {
return {
ProgressBar:"0%",
}
}
//function on change to upload and make progress
fileSelected(e) {
let fd = new FormData();
fd.append('fileInput', $("#file")[0].files[0], $("#file")[0].files[0].name);
axios.post("/admin/chatFileUpload", fd, {
onUploadProgress: function (uploadEvent) {
this.ProgressBar = Math.round((uploadEvent.loaded / uploadEvent.total)*100) + '%';
$(".inner-progressBar").css("width", this.ProgressBar);
}
});
},
//getting progress bar value in text which only returns preset value
getProgressBar() {
return this.ProgressBar;
},
You need to make getProgressBar() a computed property instead of a method.
computed: {
getProgressBar() {
return this.progressBar;
}
}
Also, you should use camel case or snake case for your variables.
The problem is the scoping of this in the code below:
onUploadProgress: function (uploadEvent) {
this.ProgressBar = Math.round((uploadEvent.loaded / uploadEvent.total)*100) + '%';
Because this is a new function it has its own this value, it does not use the this value from the surrounding code.
The simplest way to fix this is to use an arrow function:
onUploadProgress: (uploadEvent) => {
this.ProgressBar = Math.round((uploadEvent.loaded / uploadEvent.total)*100) + '%';
An arrow function retains the this value from the surrounding scope.
I also suggest getting rid of the jQuery line starting $(".inner-progressBar"), that shouldn't be necessary once you fix the this problem as it will be handled by the template instead.
Further, it's unclear why you have a getProgressBar method at all. If it is just going to return ProgressBar then you can use that directly within your template without the need for a method.
As seen here the selectors id #username is binded twice and nested. In the first binding, the value can be set with $(this).val(); and the be used in the second, nested binding for the Semantic-UI API.
But what if I have several elements like element_1, element_2 etc?
Right now, I'm using this code, but the event is fired for each element that matches the wildcard [id^=unbind_]and not only (like it should be) for the clicked element:
$(document).on('click','[id^=unbind_]', function(){
var permission=$(this).attr('data-value');
var id=$(this).attr('id');
var role_id=$(this).attr('data-roleid');
//console.log('Permission:' + id);
$('[id^=unbind_]')
.api({
action: 'unbind permissions',
on: 'now',
method: 'DELETE',
data: { 'permission': permission},
onSuccess: function(data) {
console.log('SUCCESS: ' + id);
remove_element(id);
decr('#role_cnt_' + role_id);
}
});
});
I have this script:
<aui:script use="aui-node,aui-io-request,aui-base,event">
AUI().use('event', 'aui-node', 'aui-base', function (A) {
var inputObject = A.one('#_Tend_ApplicationMain_WAR_ETenderportlet_vrednost').on('keyup', function (event) {
alert("Hi you have performed On change Event and Thank You");
});
})
</aui:script>
Why doesn't the alert ever appear?
Your code has multiple issues:
You do not need to specify an AUI().use(//... if you are using <aui:script> with the use attribute.
You only need to specify the aui-node module as an argument to the use attribute.
You most likely do not want to set inputObject equal to the return value of the on method. Instead it seems that you would want to do var inputObject = A.one('#id');.
A change event is not the same as a keyup event, so either your .on('change', function(event) { //... or your alert message which claims that it is an onchange event is incorrect.
You may have an issue with your A.one('#_Tend_ApplicationMain_WAR_ETenderportlet_vrednost') failing to find the element (check the browser logs to find out if this is true). If it is, your element may have a partially generated prefix which can be obtained using <portlet:namespace />.
If you put all that together:
<aui:script use="aui-node">
// possibly change the A.one() argument to '#<portlet:namespace />_Tend_ApplicationMain_WAR_ETenderportlet_vrednost'.
var inputObject = A.one('#_Tend_ApplicationMain_WAR_ETenderportlet_vrednost');
inputObject.on('keyup', function (event) {
alert("Hi you have performed On keyup Event and Thank You");
});
</aui:script>
Here's a runnable example:
YUI().use('aui-node', function(A) {
var inputObject = A.one('#_Tend_ApplicationMain_WAR_ETenderportlet_vrednost');
inputObject.on('keyup', function (event) {
alert("Hi you have performed On keyup Event and Thank You");
});
});
<script src="https://cdn.rawgit.com/stiemannkj1/701826667a70997013605edcd37e92a6/raw/469fe1ae297e72a5a80eb9015003b7b04eac735e/alloy-ui-3.0.1_aui_aui-min.js"></script>
<link href="https://cdn.rawgit.com/stiemannkj1/90be22de7f48c729b443af14796d91d3/raw/a9f35ceedfac7fc0559b121bed105eaf80f10bf2/aui-css_css_bootstrap.min.css" rel="stylesheet"></link>
<input id="_Tend_ApplicationMain_WAR_ETenderportlet_vrednost" />
I've got a nested grid within my grid, and it works perfectly, but the client doesn't like to use the arrow on the left and asked for a button to be added in order to show the child grid.
The example on the Kendo website shows how to automatically open the first row, I just want a way to expand the grid from a custom control in the same way that the left selector does it.
I've got the custom command working, and it executes the sample code, but I just need some help with the javascript required to make it work for the current row.
columns.Command(command =>
{
command.Edit().Text("Edit").UpdateText("Save");
command.Destroy().Text("Del");
command.Custom("Manage Brands").Click("showBrandsForAgency");
And the js with the standard example of opening the first row:
function showBrandsForAgency(e) {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
Please help by giving me the js required to expand the row clicked and not the first row?
* EDIT *
Modified the solution provided by Atanas Korchev in order to get it to work on only the button and not the whole row.
I'd prefer a solution that uses the function showBrandsForAgency instead of a custom funciton but this does the job:
$(document).ready(function () {
$("#grid").on("click", "a", function (e) {
var grid = $("#grid").data("kendoGrid");
var row = $(this).parent().parent();
if (row.find(".k-icon").hasClass("k-minus")) {
grid.collapseRow(row);
} else {
grid.expandRow(row);
}
});
});
You can try something like this:
$("#grid").on("click", "tr", function(e) {
var grid = $("#grid").data("kendoGrid");
if ($(this).find(".k-icon").hasClass("k-minus")) {
grid.collapseRow(this);
} else {
grid.expandRow(this);
}
});
When using jQuery on the function context (available via the this keyword) is the DOM element which fired the event. In this case this is the clicked table row.
Here is a live demo: http://jsbin.com/emufax/1/edit
Same results just Simpler, faster, and more efficient:
$("#grid").on("click", "tr", function () {
$(this).find("td.k-hierarchy-cell .k-icon").click();
});
Inside a jQuery loop, I'm trying to attach a click event to a dynamically created anchor tag which is contained in an LI element. The LI itself is dynamically created inside a static UL element. For some reason nothing gets fired when the anchor is clicked. Here is a simplified version of the problematic code:
$.each($.MyProject.cities, function (index, city) {
$('<li></li>').html($("<a></a>").attr("href", "javascript:void(0)").click(function (event) {
console.info("Anchor clicked!");
event.preventDefault();
return false;
}).html($("<span></span>").text(city.FullName).attr("class", "autoText"))).appendTo($("#visiblecities"));
});
where visiblecities is the id of the UL element and cities is a collection on which the loop iterates.
Any idea why the click event is not working?
Use event delegation to set up a single event handler that will react to all <a> elements, even if they're added after the code executes:
$('#visibleCities').on('click', 'a', function(event) {
console.info('Anchor clicked!');
event.preventDefault();
return false;
});
Though, as gdoron mentioned in the comments, your <a> elements don't currently have any content so they won't actually be clickable.
use .on.
$('a').on('click',function(){
//code here
});
Try
$('li a').on('click',function()
{
//code here
});
$.each($.MyProject.cities, function (index, city)
{
$('<li></li>').html($("<a></a>").attr("href", "javascript:void(0)")).appendTo($("#visiblecities"));
});
use live method instead of click
$.each($.MyProject.cities, function (index, city) {
$('<li></li>').html($("<a></a>").attr("href", "javascript:void(0)").live("click",function (event) { console.info("Anchor clicked!"); event.preventDefault(); return false; })).appendTo($("#visiblecities"));
});