1

I am trying to pass attributes and their values to javascript function from onclick event but they are returned undefined.

<script type="text/javascript">

function addParameters(control) {
         alert(control._userid);
        alert(control._flag);
}

<button text="Button" ID="btn1" _userid="datatest" _flag="datafromdatabaase" title="Add this to the list" onclick="addParameters(this);"> Button</button>
JOZO
  • 99
  • 1
  • 10
  • Possible duplicate of [Get all Attributes from a HTML element with Javascript/jQuery](http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery) – Lucio Oct 10 '15 at 02:00
  • You should not use arbitrary attributes of your own making that do not exist in HTML. Use custom data attributes instead. – CBroe Oct 10 '15 at 02:28

2 Answers2

2

You cannot access those custom attributes directly like that. You need to access them through the attributes property of the element. Try this:

<button text="Button" ID="btn1" _userid="datatest" _flag="datafromdatabaase" title="Add this to the list" onclick="addParameters(this);"> Button</button>

<script type="text/javascript">

function addParameters(control) {
  alert(control.attributes._userid);
  alert(control.attributes._flag);
}
</script>

And if you're trying to get the values of those attributes, try this:

<button text="Button" ID="btn1" _userid="datatest" _flag="datafromdatabaase" title="Add this to the list" onclick="addParameters(this);"> Button</button>

<script type="text/javascript">

function addParameters(control) {
  alert(control.attributes._userid.nodeValue);
  alert(control.attributes._flag.nodeValue);
}
</script>
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • Thank you so much, I spent half day trying to figure it out why it does not work on chrome. You are awesome, thanks again. – JOZO Oct 12 '15 at 13:09
1

I suggest you add id to the button element and then bind click event listener using that id:

// Html
<button id="btn1" _userid="1" flag="true"> </button>

//Javascript
document.getElementById("btn1").addEventListener('click', click);

function click(event){
    var attrs = event.target.attributes;
    var userid = attrs._userid;
    var flag = attrs._flag;
}

I recommend this approach over inlined onclick javascript event because this way you keep separated the html from the javascript. The html is reponsible for the view and representing the data. The javascript is responsible for the interactions with the view and the functionality. This way the representation of the data and the functionality are separated and distinct.

Dejan Bogatinovski
  • 610
  • 1
  • 6
  • 21