<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.
<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.
Share Improve this question edited Feb 1, 2015 at 16:38 Deduplicator 45.7k7 gold badges72 silver badges123 bronze badges asked Jul 24, 2012 at 17:11 YatrixYatrix 13.8k17 gold badges54 silver badges82 bronze badges 7 | Show 2 more comments3 Answers
Reset to default 15Try like this:
<select data-myattr="123" id="cboTest"
onchange="SayHello(this.getAttribute('data-myattr'))">
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.
Something like getAttribute()
should do
Here's an example:
<select data-myattr="123" id="cboTest"
onchange="SayHello(this.getAttribute('data-myattr'))">
<option>1</option>
<option>2</option>
</select>
Also, I'd try avoiding the use of inline scripts since they make HTML messy. Use addEventListener
/attachEvent
(older IE) instead.
this.dataset.myattr
(won't work in "shitty" browsers) – Šime Vidas Commented Jul 24, 2012 at 17:13:)
– Šime Vidas Commented Jul 24, 2012 at 17:17