-2

How do I get the data attributes "name" and "description" in javascript? (user clicks on button, display value)

<form action="http://serverhost/postdata" method="POST">
  <script src="myscript.js" class="blue-button" 
  data-name="aaa" 
  data-description="bbb"
  </script>
< /form>
Ivar
  • 6,138
  • 12
  • 49
  • 61
001
  • 62,807
  • 94
  • 230
  • 350
  • Possible duplicate of [Get list of data-\* attributes using javascript / jQuery](https://stackoverflow.com/questions/4187032/get-list-of-data-attributes-using-javascript-jquery) – miken32 Apr 06 '18 at 23:32
  • Not jQuery. No dup. – Randy Casburn Apr 06 '18 at 23:33
  • 1
    @RandyCasburn It's got both. But you like this one better? https://stackoverflow.com/questions/33760520/get-data-attributes-in-javascript-code Or this one: https://stackoverflow.com/questions/16566299/html-data-attribute-as-javascript-parameter – miken32 Apr 06 '18 at 23:33
  • 1
    Possible duplicate of [get data attributes in JavaScript code](https://stackoverflow.com/questions/33760520/get-data-attributes-in-javascript-code) – DrevanTonder Apr 06 '18 at 23:35
  • They are all sooooo indirect. This is a simple, direct question. Requires a simple, direct answer. But the folks with giant rep like you can decide. :-) – Randy Casburn Apr 06 '18 at 23:40

2 Answers2

4

Like this:

document.querySelector('script.blue-button').dataset

Here is the reference:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
1

First you should close the opening script tag (makes the syntax high lighting work and is easier to read)

<form action="http://serverhost/postdata" method="POST">
  <script src="myscript.js" class="blue-button" 
  data-name="aaa" 
  data-description="bbb">
  </script>
</form>

Then all you would have to do is

document.querySelector('script.blue-button').dataset
Sheshank S.
  • 3,053
  • 3
  • 19
  • 39