getting the element's id from on click with (this)


To initiate the onclick event, I have this

 [], (btnAddVendorDropDown) => {
  btnAddVendorDropDown.addEventListener('click', onAddVendorDropDownClick, false);

The function is

function onAddVendorDropDownClick(e) {

    addNewClass(modal, 'is-active');
    addNewClass(modalAddVendorDropDown, 'is-active');

    const test = $(this).attr('id');
    return test;

So what I'm trying to do is when a user clicks btnAddVendorDropDown, the function onAddVendorDropDownClick is called. I need to grab the id from the element. When I do console.log of the element attribute id from inside the function, I get exactly what I need. The problem I'm running into is when I try to grab it from outside the function, I keep getting undefined. I don't understand how I can grab the id once it calls this function from outside this function.

I tried this

var num = onAddVendorDropDownClick(); 
console.log("the function return is " + num);

Which is what shows undefined.


this is related directly to the caller's scope. This means that without "binding" a scope to your event handler, this is going to refer to your main application scope, and not the scope that jquery passes as you chain functions.

You can either wrap the event object's target:

function onClickHandler(e) {

Or you can use $(this) within the jquery context of a click handler:

$('#my-button').on('click', function(e) { $(this).attr('id'); });

The last example works because it is occurring inside a JQuery closure, so it retains the scope from the previous function. Outside of a closure, this means something else.

By : Soviut

$(this) is JQuery context, and you are inside javascript function. You can change the click button to JQuery to use it:

var test; 
    test = $(this).attr('id');
<script src=""></script>
<button id="btnTeste">

If I am reading this correctly, Message would contain a List<MessageUser>.

If that's the case then this should get you close:

var List<Message> messages = 
    ( from m 
      in db.Messages 
          m.UserID == userid || m.MessageUsers.Any(mu => mu.UserID == userID) 
      select m).ToList();
By : Sam Axe

This video can help you solving your question :)
By: admin