Rawan Mansour
Rawan Mansour

Reputation: 111

Pass this and comma separated value as arguments to function

I have a function that's create buttons dynamically, and onclick I Pass some arguments from click event to function . the arguments that's I passed is: this and the second is a comma separated string . my problem is when I passed this arguments I got this error:

Unexpected end of input

that's the button:

<button class="btnCustom" onclick="getCustomItems(this, ' + CustomIDs + ')" type="button">...</button>

CustomIDs ="3,4,5";

and the function:

function getCustomItems(e, CustomIDs) {
    var IDs = CustomIDs ;
}

How can I pass a comma separated this object and CustomIDs as arguments to function?

Upvotes: 0

Views: 3646

Answers (4)

FYP
FYP

Reputation: 153

Try this.

onclick="getCustomItems(this, \'' + CustomIDs + '\')"

Upvotes: 0

Bharat Choudhary
Bharat Choudhary

Reputation: 186

If your Ids are getting generated dynamically, try to set your customIds as an attribute on that button, and simply just pass 'this' as keyword in your function, and inside your function fetch your ids from attribute using this.

  <button class="btnCustom" onclick="getCustomItems(this)" customIDs="3,4,5"  type="button">...</button>


 function getCustomItems(e) {
      var customIDs= e.getAttribute('customIDs');
      console.log(customIds);
       //3,4,5   
      var ids= customIds.split(',');
       console.log(ids);
       //[3,4,5]
      }

Upvotes: 2

ProblemsEverywhere
ProblemsEverywhere

Reputation: 547

You can update the variable of an Id and pass it to the function as a variable

var CustomIDs='my id custom'

<button class="btnCustom" onclick="getCustomItems(this, CustomIDs)" type="button"></button>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44125

You're currently passing a string + CustomIDs + into your function - try a variable:

onclick="getCustomItems(this, CustomIDs)"

Upvotes: 1

Related Questions