Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a custom attribute to a function?

<select data-myattr="123" id="cboTest" 
        onchange="SayHello(this.data-myattr)">

This doesn't work. If I take the data-off of it it, it works, but from what I've read, it is html5 safe to do it that way. However, doing it that way, I get: "Microsoft JScript runtime error: 'myattr' is undefined".

This is my super-complex function:

function SayHello(msg) {
    alert(msg);
}

Thanks in advance.

like image 207
Yatrix Avatar asked Jul 24 '12 17:07

Yatrix


People also ask

How do I add a custom attribute to an element?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.

How do you pass attributes in HTML?

the data attribute value passed to custom element can be used while rendering the element. Let's look for the code required on the JavaScript side to extract the value passed with the attributes. In the above code, we are accessing the data sent in the attributes using the variable value “this. attributes”.

What's a custom attribute?

Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.

Can you use custom HTML attributes?

You can add custom HTML attributes to pages and page elements, which are rendered on the HTML tag of the page element. For example, this is useful when working with third-party frameworks that render page elements differently based on certain attributes.


2 Answers

Try like this:

<select data-myattr="123" id="cboTest" 
        onchange="SayHello(this.getAttribute('data-myattr'))">
like image 186
Engineer Avatar answered Oct 13 '22 00:10

Engineer


The expression:

onchange="SayHello(this.data-myattr)">

Is being interpretted as this.data minus myattr. You'd have to use:

onchange="SayHello(this.getAttribute('data-myattr'))"

instead.

like image 28
Mike Christensen Avatar answered Oct 13 '22 00:10

Mike Christensen