4

I want to pass id value of an element to a jquery click function .

Here is the code snippet

function maintest() {
   var buttonElem = $('<button>').attr({"id" : "buttonMain" }).css ({"cursor" :"pointer"}).text("Click me!").click(function() {
      buttonClicked ();
   });
   
   $("#mainDiv").append(buttonElem);
  }
   
  
  function  buttonClicked () {
    alert("button clicked");
  }
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload ="maintest()">
  <div id="mainDiv"></div>
</body>
</html>

I want to pass id value "buttonMain" to " buttonClicked" function ,

This is what I tried


function maintest() {
   var buttonElem = $('<button>').attr({"id" : "buttonMain" }).css ({"cursor" :"pointer"}).text("Click me!").click(function(this.id) {
      buttonClicked (this.id);
   });

   $("#mainDiv").append(buttonElem);
  }


  function  buttonClicked (elem) {
    alert("button clicked");
    alert("passed elem id value"+ elem);
  }
2
  • I am new to jquery, please feel free to correct me Commented Feb 10, 2020 at 11:23
  • 4
    Change function(this.id) { to function() { Commented Feb 10, 2020 at 11:26

1 Answer 1

6

this.id should not be in the function parameter list. this is passed implicitly, the first argument to a click handler function is the Event object.

function maintest() {
  var buttonElem = $('<button>').attr({
    "id": "buttonMain"
  }).css({
    "cursor": "pointer"
  }).text("Click me!").click(function() {
    buttonClicked(this.id);
  });

  $("#mainDiv").append(buttonElem);
}

function buttonClicked(elem) {
  console.log("button clicked");
  console.log("passed elem id value "+ elem);
}
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body onload="maintest()">
  <div id="mainDiv"></div>
</body>

</html>

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

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.