I've got stuck at one issue that, I am getting string from server side as one bottle only. I am assigning that string to data attribute like
var uom = serverSideValue // Contains ["one bottle only"]
<div class="uomClass" data-uom="+ JSON.stringify(uom) +"></div>
But when I inspect that element in developer tools, it is appearing like
data-uom="["one" only"]
If not JSON.stringify
data-uom="one" only
When I am trying to access uom, like below
$('.uomClass').data('uom')
above line of code giving result as only one instead of one water bottle
What I am doing wrong here. I am dynamically constructing the uom html above. Please guide me through the right way. Thank you.
I've got stuck at one issue that, I am getting string from server side as one bottle only. I am assigning that string to data attribute like
var uom = serverSideValue // Contains ["one bottle only"]
<div class="uomClass" data-uom="+ JSON.stringify(uom) +"></div>
But when I inspect that element in developer tools, it is appearing like
data-uom="["one" only"]
If not JSON.stringify
data-uom="one" only
When I am trying to access uom, like below
$('.uomClass').data('uom')
above line of code giving result as only one instead of one water bottle
What I am doing wrong here. I am dynamically constructing the uom html above. Please guide me through the right way. Thank you.
Share Improve this question edited Feb 22, 2018 at 10:39 Sivakumar Tadisetti asked Feb 22, 2018 at 10:30 Sivakumar TadisettiSivakumar Tadisetti 5,0517 gold badges38 silver badges61 bronze badges 4-
2
The issue is because the JSON being output also contains
"
characters which is conflicting with the quotes around the attributes in your HTML. You need to HTMLEncode the JSON before storing it in the attribute – Rory McCrossan Commented Feb 22, 2018 at 10:36 -
1
You could start with:
data-uom='+ JSON.stringify(uom) + '
- but if you have["there's one bottle only"]
it will fall over with the same issue. – fdomn-m Commented Feb 22, 2018 at 10:38 - 1 The first block with two lines of code suggests that the first line is javascript, while the second line looks like HTML with some javascript inserted in the wrong way. The two languages cannot be mixed in that way. Please make a good distinction between what is actually javascript and what is actuallty HTML. – Peter B Commented Feb 22, 2018 at 10:45
- Hi @RoryMcCrossan your suggestion helped me to solved the issue. Thank you. – Sivakumar Tadisetti Commented Feb 22, 2018 at 11:02
1 Answer
Reset to default 8I solved the issue by taking Rory McCrossan suggestion in the ments section below the question. I've used encodeURIComponent() and decodeURIComponent()
HTML Code
var uom = serverSideValue // Contains ["one bottle only"]
<div class="uomClass" data-uom="+ encodeURIComponent(uom) +"></div>
jQuery Code
var $uom = decodeURIComponent($('.uomClass').data('uom'))
Now I am getting the correct results. Thank you Rory McCrossan for your suggestion.