Setting onclick property for input - javascript

I need to set onclick property to the newly created element (input tag). It should be function with arguments. I use this: addButton.onclick = addToBasket(aHref[i].innerHTML, aHref[i].href);
But the problem is that this function calls automatically when window is loaded, but I need simply to set property. By the way if I use function without arguments like this: addButton.onclick = addToBasket; it works (isn't called automatically).

Use instead:
addButton.onclick = function(){
addToBasket(aHref[i].innerHTML, aHref[i].href);
}
onclick expects a function-definition. Another possibility is:
addButton.onclick = addToBasket;
But in this last one you will need to get the args from the function's inside, or with global variables.
It is because when you use () you are invoking the function-definition which will return some value or undefined.

You probably want this:
addButton.onclick = function(){ addToBasket(aHref[i].innerHTML, aHref[i].href)};
The difference is that the addToBasket call here is done on click, not before.

Related

how to insert onclick attribute into a span? [duplicate]

This is my function and it should change the onClick attribute of the HTML input, but if I use
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
it does not work at all, but if I use
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
the function executes by itself!
Any ideas what code do I have to use to change the onCLick attribute WITHOUT executing the function, before the button is clicked?
Here is the full function, if it matters:
function showLED(id){
if(color == 0){
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
document.getElementById('buttonLED'+id).value="light is on";
//document.getElementById('buttonLED'+id).disabled = false;
}else{
document.getElementById('buttonLED'+id).onclick = "writeLED(1,0)";
document.getElementById('buttonLED'+id).value="light is off";
//document.getElementById('buttonLED'+id).disabled = false;
}
}
Well, just do this and your problem is solved :
document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')
Have a nice day XD
You want to do this - set a function that will be executed to respond to the onclick event:
document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;
The things you are doing don't work because:
The onclick event handler expects to have a function, here you are assigning a string
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
The line onclick = writeLED(1,1) means that you want to immediately execute the function writeLED(arg1, arg2) with arguments 1, 1 and assign the return value; you need to instead create a function that will execute with those arguments and assign that. The topmost answer gave one example - another is to use the bind() function like so:
var writeLEDWithSpecifiedArguments = writeLED.bind(this, 1,1);
document.getElementById('buttonLED'+id).onclick = writeLEDWithSpecifiedArguments;
Using Jquery instead of Javascript,
use 'attr' property instead of 'setAttribute'
like
$('buttonLED'+id).attr('onclick','writeLED(1,1)')
You are not actually changing the function.
onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.
Another problem is your variable color seems out of nowhere.
Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)
Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.
document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};
This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.
First we'll select the required button using query selector and for all the selected buttons we'll set the onclick attribute with a function that needs to be called by clicking on the buttons.
You can write the code for required work you want to do by clicking the button in the function defined.
Well "One of the" generalized solution to your to your problem can be achieved by the following code:
var a=document.querySelectorAll('button');
for(b=0;b<a.length;b++)
{
a[b].setAttribute("onclick","check("+b+")");
}
function check(e)
{
var sa=a[e].innerHTML;
console.log('working onclick',sa);
}

How do you remove an event listener that uses an anonymous function for passing parameters?

Apologies in advance as I have done some searching and this appears to be a fairly common question, but none of the answers I have found quite meet my needs. The closest I was able to find was How do I add and remove an event listener using a function with parameters?, but the answer there involves JQuery and I am trying to find a way to do this in just JS.
I am using anonymous functions to pass parameters through an event trigger which I believe is the correct way to do so. If temp is defined by some calculations based on the state at the time the event is added, I want to add the listener as follows:
item.addEventListener("click", function(){myOnClickFunction(temp)});
However, I want to be able to remove the event dynamically if certain conditions are met.
item.removeEventListener("click", function(){myOnClickFunction(temp)});
This does not work as the inline function is anonymous and cannot be referenced for matching up the event listener (plus temp is likely different anyway). Since temp is calculated at the time of the trigger, I cannot store a reference outside of the anonymous function with something like this:
var listener = function() {
var temp = calculate(arg1, arg2, event);
myFunction(temp);
};
window.addEventListener('click', listener, false);
so that I can later call:
window.removeEventListener('click', listener, false);
myOnClickEvent(temp){
//My code and calculations here
document.removeEventListener("keypress", arguments.callee);
}
is also not working, although I'm less confident as to how that method is supposed to work.
How can I remove this function dynamically? In some cases, I might be able to refactor my code so that all variables that need to be passed are stored globally and rewritten constantly, but that sounds like messy code. Plus, in some cases the trigger event is one of the arguments that needs to be passed so I don't think I could make that happen. Any ideas?
You can create an object, whose properties are the temp values, and whose values are myOnClickFunction bound to that temp. For example:
const boundFns = {};
// acquire temp somehow
const boundFn = () => myOnClickFunction(temp);
boundFns[temp] = boundFn;
item.addEventListener("click", boundFn);
Then, when you need to remove the listener, retrieve the appropriate bound function:
item.removeEventListener("click", boundFns[temp]);
If a temp may be used more than once, check if it exists in boundFns first:
const boundFns = {};
// acquire temp somehow
if (!boundFns[temp]) {
boundFns[temp] = () => myOnClickFunction(temp);
}
const boundFn = boundFns[temp];
boundFns[temp] = boundFn;
item.addEventListener("click", boundFn);
If temp cannot be be used reliably as a unique object key (for example, if it's an HTMLElement), you can use a Map instead, which is like an object, but whose keys can be anything, not just strings:
const boundFns = new Map();
boundFns.set(temp, boundFn);
// ...
item.removeEventListener("click", boundFns.get(temp));

Function parameter evaluates to undefined

When dynamically creating an element of type select, there are two problems when setting the onclick method:
It is impossible to simply set the onclick with element.onclick="updateInput(this.articleIndex)";
This results in a final HTML tag where no onclick is shown at all.
When set by e.setAttribute("onclick","updateInput(this.articleIndex)");, it does appear in the final HTML. And the updateInput method does get called.
However the functionality seems to be broken, as the argument always evaluates to undefined
Here a simple example of my problems:
var selectElem = document.createElement("select");
selElem.id="articleSelector_"+this.articleIndex;
console.log("the index of the article is " + this.articleIndex);
selElem.setAttribute("onclick","updateInput(this.articleIndex);");
//selElem.onclick="updateInput(this.articleIndex)"; //this does not work
The log shows the correct number. Inside the updateInput method, the argument is of value undefined instead of the number previously shown in the log.
Try attaching handlers with pure Javascript, and not with HTML, without onclick = "... (which is as bad as eval).
The this in your script refers to the calling context of the function - what is it?
You might want:
element.addEventListener('click', () => {
updateInput(this.articleIndex);
});
(arrow functions retain the this of their surrounding scope)
it is impossible to simply set the onclick with element.onclick="updateInput(this.articleIndex)";
What that code does is it assigns the string "updateInput(this.articleIndex)" to the onclick which makes no sense and certainly not what you want.
Even if you remove the quotes:
element.onclick = updateInput(this.articleIndex);
It is still incorrect because it assigns the result of the updateInput() function to the onclick which is again not what you want.
You need to assign a function name to the onclick like this:
element.onclick = updateInput;
However, this doesn't allow you to pass a parameter as you wish. To do so, you need to use an anonymous function:
element.onclick = function() {
updateInput(this.articleIndex)
};
When set by e.setAttribute("onclick","updateInput(this.articleIndex)");, it does appear in the final HTML. And the updateInput method does get called.
This works because it sets the attribute onclick and it is a string type, so everything is correct. It is equivalent to using the anonymous function above. The only difference is this, which in this case refers to the element itself, while in the above code it depends on the context that the code appears in. That's why in this case the argument always evaluates to undefined because the select element doesn't have an articleIndex property.
The problem is the value of the context this when that element is clicked, the context this is not available anymore at that moment.
You have two ways to solve this problem:
You can use the function addEventListener to bind the event click, and bind the function/handler with the desired context this:
The function bind binds a specific context to a function.
selElem.addEventListener('click', updateInput.bind(this));
function updateInput() {
console.log(this.articleIndex);
}
As you need a specific value, you can use data attributes. That way, you don't need to worry about the context this.
selElem.dataset.articleIndex = this.articleIndex;
selElem.addEventListener('click', function() {
updateInput(this.dataset.articleIndex); // Here you can get that value.
});

How To Make This Refer To My Clicked Object Javascript

button.setAttribute("onClick" , "addToCart()");
I wrote this line in creation of an element to do an action, but when i click it and deal with "this" it refers to window not the object
How can i fix this to make the click refer to my element in order to get some data from the parent ?
Don't use setAttribute for event handling. Use addEventListeners instead. For now, you could make your function like this, which uses event object that gets passed when it's called on the triggering of the event, in this case click
function addToCart(e){
var that = e.target; // use that instead of this
// more code goes here
}
And then you could just set it to the onclick property
button.onclick = addToCart; // pass the function reference

How to mimic an HTML element and add attributes to it in Javascript/jQuery

I have a method called handle_value_tag_click(value) which takes an HTML element (value) as a parameter.
I want to call this function from another function, but this time I don't have a 'ready made' HTML element ... in the initial situation I pass a this element and the function unwraps the parameters appropriately.
My guess is I have to construct the element by using a JS object. This is my attempt:
var value = new Object();
value.attr("valueType","NumericQueryValue");
value.attr("lower",lowerBound);
value.attr("upper",upperBound);
handle_value_tag_click(value);
However I get the error value.attr is not a function, how can I solve this error, or get the appropriate behavour (passing parameters to the handle_value_tag_click() function) in some other way.
what if you say this?:
var value = $("<div />");
Why don't you create an element like this:
var value = $(document.createElement("div"));
It won't be in the DOM but every jQuery method will work on it.

Categories