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>
2
  • Possible duplicate of Get all Attributes from a HTML element with Javascript/jQuery Commented Oct 10, 2015 at 2:00
  • You should not use arbitrary attributes of your own making that do not exist in HTML. Use custom data attributes instead. Commented Oct 10, 2015 at 2:28

2 Answers 2

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>

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

1 Comment

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

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.