0

How can I get the attribute ID from the button? It returns undefined. I ask this because I will have many buttons with different ID like: edit-user-21 or edit-user-22

    function edituser() {
    	var test = $(this).attr('id');
      alert(test);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-primary" id="btn-edit-2" onclick="edituser()">Edit</button>
<div id="testdiv"></div>

1
  • $(document).ready(function() { $(".btn-primary").click(function () { alert($(this).attr("id")); }); }); Commented Dec 10, 2016 at 6:39

3 Answers 3

1

Try this... when clicking on the button

<button class="btn-primary" id="btn-edit-2" onclick="edituser(this)">Edit</button>

and function will be

 function edituser(this) {
    var test = $(this).attr('id');
  alert(test);
}
Sign up to request clarification or add additional context in comments.

Comments

0

In jQuery you can access to the element by Id

$('#ID')

It should looks like this:

var myButtonId = $('#btn-edit-2')

1 Comment

But I'm populating multiple buttons with many different IDs. That's why I wanna know how to grab the ID by using the $(this) selector.
0

    function edituser() {
    	var test = $(this.id);
      alert(test);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-primary" id="btn-edit-2" onclick="edituser()">Edit</button>
<div id="testdiv"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.