Jump to content

Creating onclick JS Func from PHP


Adamhumbug

Recommended Posts

I have a function in JS that i would like to pass 2 variables to.  One is an int and one is a string.

I am struggling to get the string part right as it needs to be wrapped in quotes.

My code is :

$out.="<div onclick='newTransactionLine(".$r['id'].",".$r['direction'].")' class='transactionItem btn $class d-block mb-2' data-id='".$r['id']."' >".$r['item']."<br/>£".$r['price']."</div>";

which outputs:

<div onclick="newTransactionLine(1,OUT)" class="transactionItem btn btn-primary d-block mb-2" data-id="1">Adult Membership (£85)<br>£85.00</div>

When i click the button that gets made, i get a reference error on the word out.

I have no doubt it is very simple but i just cannot get this to work for me.

 

Link to comment
Share on other sites

See how you have data-id='".$r['id']."' for your $r['id'] variable?   Do the same thing with your direction variable.  data-direction='".$r['direction']."'

Then in your javascript code you can access these values via the dataset property on the element.

onclick="newTransactionLine(this.dataset.id, this.dataset.direction)"

 

Link to comment
Share on other sites

18 hours ago, kicken said:

See how you have data-id='".$r['id']."' for your $r['id'] variable?   Do the same thing with your direction variable.  data-direction='".$r['direction']."'

Then in your javascript code you can access these values via the dataset property on the element.


onclick="newTransactionLine(this.dataset.id, this.dataset.direction)"

 

Bingo - thanks very much!!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.