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