I have a button
<button onclick="DeletaItem('template','1234')" id="btn">Deletar_func</button>
And the function
function DeletaItem(tipo,id_cripto){
alert(tipo+id_cripto);
alert($(this).attr('id'));
}
Why the second alert is undefined?
The second alert is undefined because this does not refer to the button, it actually refers to the window object.
You need to either send this to the function, change the onclick to the following:
onclick="DeletaItem(this, 'template', '1234')"
and also change the function as follows:
function DeletaItem(button, tipo, id_cripto) {
alert(tipo + id_cripto);
alert(button.id);
}
or leave the onclick as it is and use event.target within the function instead of this.
function DeletaItem(tipo, id_cripto) {
alert(tipo + id_cripto);
alert(event.target.id);
}
try this:
$('#btn').click(function(){
alert(this.id);
});
OR
<button onclick="DeletaItem(this,'template','1234')" id="btn">Deletar_func</button>
function DeletaItem(obj,tipo,id_cripto){
alert(tipo+id_cripto);
alert($(obj).attr('id'));
alert(obj.id);
// alert(this); if uncomment this, you will see it is eqaul window object
}
when function called with onclick attribute, it's don't became an object like first one, so you can't use this; here this is window objectm but in first one, jQuery object will be passed
Related
I have spent a day trying to find the way to pass the correct context to the removeForm. The goal is to use the removeForm which is called when pressing <a class="remove_2"> remove </a> link to remove the content of the class passed to removeForm in this case "subform2". Here is what I tried:
function removeForm(tgsubf) {
var $removedForm = $(this).closest(tgsubf);
var removedIndex = parseInt($removedForm.data('index'));
$removedForm.remove();
}
$(document).ready(function() {
$('.remove_2').click(function(e){
e.preventDefault();
removeForm('.subform2')
});
}
<div class="subform2">
<a class="remove_2"> remove </a>
</div>
I know that the context depends on how I call the function but also if I call the function using removeForm('subform2') I still have this problem.
The full example is hosted here.
If you want to remove the .subform2 element that contains the .remove_2 which was clicked, you can do the following.
When your are inside an event callback you pass to jQuery, this (generally) holds the element that received the event. So you should change your code to have the following:
$('.remove_2').click(function(e){
e.preventDefault();
removeForm(this) // <-- 'this' will refer to $('.remove_2')
});
Then you can change your removeForm() to get the immediate ancestor of the element passed to it (which would be .remove_2) that has .subform2 for class and remove it, like this:
function removeForm(anchor) {
var $removedForm = $(anchor).closest('.subform2');
$removedForm.remove();
}
UPDATE
You should be able to pass a selector to removeForm to identify the ancestor, like this:
function removeForm(el, ancestorSelector) {
// Do check to ensure ancestorSelector is provided, before using it.
var $removedForm = $(el).closest(ancestorSelector);
$removedForm.remove();
}
You can update how you call it like this:
$('.remove_2').click(function(e){
e.preventDefault();
removeForm(this, '.subform2') // <-- 'this' will refer to $('.remove_2')
});
I have a variable that is attached to a function. I am trying to use that variable in an onclick event.
This is what I am doing
var show = function() {
console.log("hello");
};
$(container).append(
"<div class='info' onclick=" + show + ">Show</div>"
);
However the generated html comes out like this
<div class="info" onclick="function()" {="" console.log("hello");="" }="">
Show
</div>
Any idea how I can fix this so that when I click the div my function gets called ?
You can simply do like this, Just make show a function and call it on click.
This will work
<script>
function show() {
console.log("hello");
}
$(container).append(
'<div class="info" onclick="show()">Show</div>'
);
</script>
This is kind of an unusual approach to what you're trying to do. I think it would be more idiomatic in jQuery to either
a) define the element first, with event handler, and then append it,
$("<div>Show</div>", {
"class": "info",
on: {
click: function(e) {
console.log("Hello");
}
}
}).appendTo($(container));
or
b) append a new element and then add an event handler to it after appending it.
$(container).append("<div class='info'>Show</div>");
$(container).children('.info').last().on('click', function(e) { console.log("Hello"); });
Between those two, I'd recommend the first in this case.
The variable show is a function, Then how can you bind it with string?
The code should be like,
$(container).append("<div class='info' onClick='show()'>Show</div>");
try using :
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick="+'show()'+">Show</div>");
This will work.
The reason why your code
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick=" + show + ">Show</div>");
was not working as required as show is an object of type function, so when one uses the function name without the () the variable is replaced bu the code that it consists.
Hope it helps.
document.getElementById('divv').addEventListener("click",func)
function func(a){
alert("oooo");
}
function abc(){
document.getElementById('divv').removeEventListener("click",function(){func()});
}
<div id="divv">This is vivek</div>
<button onclick="abc()">Remove</button>
I have a button and I want to remove the onclick event on a div after I click on the button.
Just like that:
document.getElementById('divv').removeEventListener("click", func);
See the explanation about removeEventListener
document.getElementById('divv').addEventListener("click", func)
function func(a) {
alert("oooo");
}
function abc() {
document.getElementById('divv').removeEventListener("click", func);
}
<div id="divv">This is vivek</div>
<button onclick="abc()">Remove</button>
You are not adding and removing the same function, and that is why it doesn't work.
You are adding like this: .addEventListener("click", func")
And you are removing like this: .removeEventListener("click", function(){func()})
func and function(){func()} do not refer to the same function, even though they have the same result, when called.
You need to remove exactly the same way as you remove; otherwise removing won't "find" the original function you added:
function abc(){
document.getElementById('divv').removeEventListener("click",func);
}
I have some functions that are triggered when an element is clicked. The elements are stored in an array. But the value that trigger the functions change. Here is the code for the function:
// first I store the element of a list in an array
var promo = new Array(),
indexOfTheElement = 3;
$('#list li').each(function(){
promo.push($(this));
});
$(myArray[indexOfTheElement]).click(function(){
indexOfTheElement--;
// Do something
return false;
});
Edit: The element of a list are stored in an array, and the function is triggered when you click an element of the list. For example if you click the third element, the function will be triggered, and then it must work when you click the second.
It could be a scope issue, but I believe you want to use bind() and unbind() on each function call. For instance:
var foo = function(){
myArray[index].unbind("click");
index--;
//do something
myArray[index].bind("click", foo);
return false;
}
Inside you event handler unhook current event handler and set the new one, simply declare the function (not use an anonymous function) when you set the click().
$(myArray[indexOfTheElement]).click(doSomething);
function doSomething()
{
$(myArray[indexOfTheElement]).off("click", doSomething);
$(myArray[--indexOfTheElement]).click(doSomething);
return false;
}
try using live() and code inside $(document).ready()
$(document).ready(function(){
var promo = new Array(),
indexOfTheElement = 3;
$('#list li').each(function(){
promo.push($(this));
});
$(myArray[indexOfTheElement]).live('click',function(){
indexOfTheElement--;
// Do something
return false;
});
});
I have been using the following method for adding a click event to an id, I was wondering if I could do the same with a class.... I have a number of items (which are created in a for each loop) and I need to be able to click them and then pickup which was clicked... here is my existing code
$('submit-button').bind('click', submit_click);
function submit_click() {
alert('I am clicked');
}
I was wondering if there is some way to pass in a variable into my function for the click so i can check the ID?? or similar
hence this
function submit_click(element) { // notice element
alert(element + ' clicked');
}
Any help really appreciated
Thank you
EDIT
I have tried the following and in debug "elem" is undefined...
$('.clear').bind('click', clear_click($(this)));
function clear_click(elem)
{
alert(elem.attr("id"));
}
WORKING SOLUTION
I have the working solution but I don't fully understand why, I would love to know why it works..
First of all I tried
$('.clear').bind('click', clear_click($(this)) );
This seemed to work "BUT" when I loaded the page it enter the "clear_click" method without being clicked - strange...
Then I tried this..
$('.clear').bind('click', function() { clear_click($(this)) } );
This works great! But I don't understand why I must pass a function and then within this function call my clear_click.
Can anyone explain why 1 works and the other doesn't?
Whenever I need to call a callback function or similar I should first open a function() and then call the method inside the function?
$(".yourclass").click ( function() {
$(this).attr ( "id" ); //S(this) returns the current element
});
and you can code like this
$('.yourclass').bind('click', function() { submit_click($(this)) });
function submit_click(elem)
{
alert ( elem.attr ("id" ) );
}
Edit
$('.clear').bind('click', function() { clear_click($(this)) });
function clear_click(elem)
{
alert(elem.attr("id"));
}
This will work fine for you.
Update
To answer your second question:
You can bind a function as a second argument when using the click event, but you cant bind a function and apply arguments. On the other hand, there is no need to send this as an argument to the clear_click function since the this keyword inside the function refers to the element itself:
So this works in your case:
$('.clear').bind('click', clear_click);
function clear_click() {
alert(this.id);
}
Sending this as an argument is not needed and bad coding:
$('.clear').bind('click', clear_click(this));
In the event handler, the first argument is the event object. You can extract the clicked element from that object using currentTarget or target. In jQuery, this always refers to the currentTarget in the event handler context:
var handler = function(e) {
var id = this.id; // this == e.currentTarget
}
$('submit').click(handler); // .click(fn) is shorthand for .bind('click', fn)
More examples:
$('submit').bind('click', function(e) {
console.log(e.target) // the target that was clicked on
console.log(e.currentTarget) // the element that triggered the click
console.log(this) // the same as above
});
Just add $(this) to your function, You don't need to send any parameters because you are still in the context of the clicked element.
function submit_click() { // notice element
alert($(this).attr('id') + ' clicked');
}
When you bind a handler to a function, the clicked element will be the first argument
$('.submit-button').click(submit_click);
function submit_click(element){
//element is the .submit-buttom element
alert(element+' was clicked');
alert($(element)+' was clicked');
}
This should work:
$('.submit-button').bind('click', submit_click($(this)));
function submit_click(element) { // notice element
alert($(element).attr("id") + ' clicked');
}