Tom
Tom

Reputation: 2661

passing arguments to a click event in jQuery

I have an onclick event that passes a $(this) argument to a function.

<tr class="myTr">
  <td>
    Han Solo
  </td>
</tr>  

<script>
$('body').on('click','.myTr',function(){
  doSomething($(this));
});
</script>

Now, I want to add another step. I want to show a button, and after this button is click, doSomething() is supposed to be called.

<tr class="myTr">
  <td>
    Han Solo
  </td>
</tr>  
<button id="myBtn" style="display:none">Submit</button>

<script>
  $('body').on('click','.myTr',function(){
    $('#myBtn').show();
  });
  $('#myBtn').click(function(){
    doSomething(???);
  });
</script>

How do I pass the $(this) to the second click event?

I could easily store the $(this)as a tag of the button, something like this:

$('body').on('click','.myTr',function(){
  $('#myBtn').attr('origin', $(this));
  $('#myBtn').show();
});
$('#myBtn').click(function(){
  var tr = $(this)attr('origin');
  doSomething(tr);
});

But I was wondering if there is a more elegant way to solve this?

Upvotes: 0

Views: 96

Answers (2)

Roljhon
Roljhon

Reputation: 1339

Simply use $.proxy from jQuery

$('body').on('click','.myTr',function(){
  $('#myBtn').show();

    $('#myBtn').off('click').on('click', $.proxy(function(e) {
        doSomething(this)
        // how you access the context of the button is using $(e.currentTarget)
    }, this));
});


window.doSomething = function(elem){
	console.log(elem)
}
#myBtn{
	display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="myTr" value="test">
<input type="button" id="myBtn" value="button">

Upvotes: 1

epascarello
epascarello

Reputation: 207511

You need to set the state in some manner

Data attribute:

$('body').on('click','.myTr',function(){
  $('#myBtn').data('origin', $(this)).show();
});
$('#myBtn').click(function(){
  var tr = $(this).data('origin');
  doSomething(tr);
});

Local Variable

(function () {
    var active;
    $('body').on('click','.myTr',function(){
      active = $(this);
      $('#myBtn').show();
    });
    $('#myBtn').click(function(){      
      doSomething(active);
    });
}());

Rebind the event:

$('body').on('click','.myTr',function(){
  var active = $(this);
  $('#myBtn')
    .off("click.tr")
    .on("click.tr", function () {
      doSomething(active);
    })
    .show();
});

CSS class:

$('body').on('click','.myTr',function(){
  $(".myTr.active").removeClass("active");
  $(this).addClass("active");
  $('#myBtn').show();
});
$('#myBtn').click(function(){
  var tr = $(".myTr.active");
  doSomething(tr);
});

Upvotes: 1

Related Questions