Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass an array from onClick to javascript function?

In PHP I can write a function like this:

function myFunction(myArray)
{
    foreach(myArray)
    {
        // do stuff with array
    }
}

Then I can call it like this (maybe ugly, but still works):

myFunction(array("string1","string2"));

I want to do something similar with JavaScript but can't figure out if it's possible to pass arrays to functions like that. This is my psuedo-function:

function myFunction(myArray)
{
    for (index = 0; index < myArray.length; ++index)
    {
        // do stuff with array
    }
}

I want to call it from a button using onClick like this:

<input type="button" value="myButton" onClick="return myFunction(array("string1","string2"))">

Can this be accomplished in a simle way?

like image 587
Torbjörn Loke Nornwen Avatar asked Oct 27 '25 10:10

Torbjörn Loke Nornwen


1 Answers

Yes, it's possible. You'd probably want to use array initializer syntax (aka an "array literal"), and you need to mind your quotes:

<input type="button" value="myButton" onClick="return myFunction(['string1','string2'])">

If your attribute value is quoted with double quotes, you can't use a literal double quote within the value. The easiest thing is to use single quotes, although since the text of attribute values is HTML text (something people tend to forget), you could use &quot; if you liked. (I wouldn't. :-) ) And the fact that the text is HTML is something to keep in mind for the contents of the array...

It may well not be desirable, though. You might consider using modern event handling techniques to hook up the handler, for instance:

document.querySelector("input[type=button][value=myButton]").addEventListener("click", function() {
    myFunction(['string1','string2'])
}, false);

Or if you have multiple of them:

const handler = () => {
    myFunction(["string1","string2"]);
};
for (const element of document.querySelectorAll("input[type=button][value=myButton]")) {
    element.addEventListener("click", handler, false);
}

In that latter case, if all the elements are in some container (and ultimately they are, even if the container is just document.body), you might be able to use event delegation to hook up a single handler and then see if the event passed through the relevant element:

theContainer.addEventListener("click", function(event) {
    const button = event.target.closest("input[type=button][value=myButton]");
    if (button && this.contains(button)) {
        myFunction(["string1","string2"]);
    }
});
like image 113
T.J. Crowder Avatar answered Oct 30 '25 00:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!