1

This is the HTML attribute:

data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}"

How can get the value of the keys by javascript by the key name? Such as 'StartAt' value.

George
  • 83
  • 1
  • 5
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse – Pete Mar 04 '19 at 12:35
  • 1
    Possible duplicate of [Store JSON object in data attribute in HTML jQuery](https://stackoverflow.com/questions/8542746/store-json-object-in-data-attribute-in-html-jquery) – adiga Mar 04 '19 at 12:35

2 Answers2

1

Please see below code. we know that singleQuote will give you an error while parsing JSON. so I replace it with doubleQuote.

$(document).ready(function(){
var d=$("#data").attr('data-plugin-options');
d=d.replace(/'/g, '"');
var parsedData=JSON.parse(d);
console.log(parsedData.StartAt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='data' data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}">Some text...</p>
Negi Rox
  • 3,828
  • 1
  • 11
  • 18
0

Data in element are always a string, but you can parse it, no problem.

Here is an example how to do it

const myElement = document.querySelector('p') // here you have element object, you can use other ways to get it
const dataString = myElement.dataset.pluginOptions // here you have string of the data
const formattedDataString = dataString.replace(/'/g, '"') // your JSON is wrongly formatted, this is fix
const dataObject = JSON.parse(formattedDataString) // where you have object of the data
const dataValue = dataObject.Enabled // where you have value by key

Your JSON is also wrongly formatted, it has single quotes where JSON spec requires double quotes. You can replace it, but this can bring additional problems in case that content contains double quotes - it will crash your script. I'd suggest to look at JSON generation and change it to standard if possible.

Hope this helps

Ales Ruzicka
  • 2,770
  • 1
  • 18
  • 24
  • It gives me an error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in the line of "dataObject" – George Mar 04 '19 at 12:50
  • Sorry, I now tested it and modified the code. But issues at least in Firefox is, that your JSON string is not up to specs. In JSON you have to have double quotes around attributes, here you have single ones. – Ales Ruzicka Mar 04 '19 at 12:52
  • Thank you but it will be print an error because "pluginOptions" is not defined. – George Mar 04 '19 at 12:55
  • Can you paste your full element at least? First line must be modified to find your element, otherwise it will not work. – Ales Ruzicka Mar 04 '19 at 12:57