0

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?.

2
  • 2
    The answer is quite simple, stop using inline javascript Commented Nov 10, 2016 at 22:59
  • 1
    get rid of the .id in this.id.getAttribute('data-niq'). however i'd also suggest you to stop using inline javascript. Commented Nov 10, 2016 at 23:01

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect answer. Here is a reference on why inline javascript is bad most of the time: softwareengineering.stackexchange.com/questions/86589/…
1

you have added this.id.getAttribute('data-niq');

remove id

this.getAttribute('data-niq')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.