Boris
Boris

Reputation: 10296

How to reference button in jQuery?

In the HTML, I have a button defined like this:

<button type="button" onclick="toggleEdit();">Edit</button>

At the end of the page, I have this script I am working on:

<script language="JavaScript">
  <!--
  function toggleEdit() {
    var btn = $(this);
    var li = btn.parent();
    var textArea = li.children('.readOnly');
    ...
  }
  //-->
</script>

I cannot reference the button I have clicked in the script. The btn variable is an object, but I don't know anything else than that.

I found many examples on the internet that are using this approach:

$(document).ready(function () {
   $('#buttonID').click(function () {
   ...

but I cannot reference the button via ID because it is added dynamically. So, how do I reference it? Thanks.

Upvotes: 1

Views: 3186

Answers (2)

rockerest
rockerest

Reputation: 10518

You can pass the event into the function, and then use that.

<button type="button" onclick="toggleEdit( event );">Edit</button>

Then in your function, you can get the target of the event:

function toggleEdit( e ) {
    var btn = $( e.target );
    var li = btn.parent();
    var textArea = li.children('.readOnly');
    ...
}

Upvotes: 1

Shawn31313
Shawn31313

Reputation: 6062

Just to keep it your way, you have to tell the code that this will refer to the button instead of the actual function.

To do this you can just add an extra argument to the toggleEdit function.

The new HTML would look like this (no apply or call function needed):

<button type="button" onclick="toggleEdit(this);">Edit</button>

Then your new JavaScript would look like this:

<script language="JavaScript">
  <!--
  function toggleEdit(t) {
    var btn = $(t);
    var li = btn.parent();
    var textArea = li.children('.readOnly');
    ...
  }
  //-->
</script>

Upvotes: 2

Related Questions