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.

2

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

if you use jQuery, you should use just .data function instead of .attr('data-
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

4 Comments

It gives me an error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in the line of "dataObject"
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.
Thank you but it will be print an error because "pluginOptions" is not defined.
Can you paste your full element at least? First line must be modified to find your element, otherwise it will not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.