Le Qs Le Qs - 21 days ago 6
Javascript Question

Getting the value of attribute data-* in an inline function

I have a data attribute

data-niq
which i am using to store some data. I want to pass the data in
*-niq
to a function as a second parameter to a function.

This is the code

<button onClick="editevent(this.id,this.id.getAttribute('data-niq'));" id="mid" data-niq="niq" class="mr edit btn btn-success pull-right"> Edit</button>

<script>
function editevent(clicked_id,attri_bute){
console.log('clicked id',clicked_id);
console.log('data-niq',attri_bute);
}
</script>


and the link https://jsfiddle.net/codebreaker87/zob8dm4z/8/

When i run the code i get
TypeError: this.id.getAttribute is not a function


How can i pass the
data-niq
value in the inline function that i am calling?.

Answer

Few things here

  1. Never mix your mark up with javascript
  2. Try to bind events in javascript end.

check the following snippet.

window.onload = function() {

  var mid = document.getElementById("mid");
  mid.addEventListener('click', function() {
    editevent(this);
  })
}

function editevent(thisObj) {

  var id = thisObj.getAttribute('id');
  var dataniq = thisObj.getAttribute('data-niq');
  alert(id);
  alert(dataniq);
}
<button id="mid" data-niq="niq" class="mr edit btn btn-success pull-right">Edit</button>

Hope it helps

Comments