0

I'm trying to pass 2 variable using onClick inside of <a> tag

Here's my code:

 <a onClick="pbDiv(id=1);">Enter</a>

 <script>

 function pbDiv(id){
 alert(id);
 }

 </script>

This works perfectly as it should be.

But the problem is I need to pass 2 variable

Example of variable

id=1

name=myname

inside of onClick

Is that even possible?

tried this one onClick="pbDiv(id=1,name=name);"

seems not working to me.

3
  • 2
    Don't pass the argument name, just pass the argument value. pbDiv(1, 'foo') But even better, avoid inline listeners entirely Commented Sep 20, 2019 at 7:49
  • how can I define them inside of function? Commented Sep 20, 2019 at 7:50
  • By defining arguments for the function (like you already are for id) Commented Sep 20, 2019 at 7:51

2 Answers 2

1

In javascript, you define the name as an argument, and never pass in the name of the argument as a parameter. TypeScript (a version of javascript) does this, however.

 function pbDiv(id, name){
   alert("id: " + id + ", name: " + name);
 }
 <a onclick="pbDiv(1, 'foo');" href="#">Enter</a>

Sign up to request clarification or add additional context in comments.

2 Comments

Uncaught ReferenceError: foo is not defined at HTMLTableRowElement.onclick (3:1) im getting this error when I tried to put the onclick on table tr
Did you forget the single quotation marks around foo? So that the parameter becomes a string instead of a variable.
1

Pass object instead

<a onClick="pbDiv(options={id:1, name: 'deepak'});">Enter</a>
<script>
  function pbDiv(options) {
    alert(options.id + options.name);
  }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.