0

How can I modify the "foo" value in the following element: ?

<div id="my-element" data-request-data="bar: 1, foo: 2">

I've tried:

$('#my-element').attr('data-request-data.foo', 5);

But it doesn't work.
Can someone help me ?

3
  • 1
    To do what you're asking is possible, but it will be ugly due to the format of the value. Is it possible to change it to JSON or separate data attributes instead? Commented Jan 26, 2021 at 15:42
  • Not really, it is set that way in the CMS I work with... Commented Jan 26, 2021 at 15:48
  • Do you not have any control over the output from the CMS to the views? Commented Jan 26, 2021 at 15:51

2 Answers 2

1

You can not directly modify parts of data attribute, but what you need is simply done with splitting value after grabbing it and setting it again modified...

let newFoo = $('#my-element').attr('data-request-data').split('foo: ');
// get data value and split it

$('#my-element').attr('data-request-data', newFoo[0] + 'foo: ' + 5)
//set new


console.log($('#my-element').attr('data-request-data'))
//cheak...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my-element" data-request-data="bar: 1, foo: 2">

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

Comments

1

Ok I did it in a hard way to make a json and back to text .. I'll post it anyway it may help someone in the future

var data = $('#my-element').attr('data-request-data');
var text_to_json = convert_to_json(data);
console.log(text_to_json);
text_to_json.foo = 5;
var json_to_text = back_to_text(text_to_json);
console.log(json_to_text);
$('#my-element').attr('data-request-data' , json_to_text);


function convert_to_json(data){
  data = data.split(',');
  result = '';
  $.each(data , function(i , v){
    v = v.split(':');
    v_total = '"'+v[0].trim()+'": "'+v[1].trim()+'"';
    result += v_total+',';
  });
  return JSON.parse('{'+result.replace(/(^,)|(,$)/g, "")+'}');
}

function back_to_text(json){
  var json_txt = JSON.stringify(json);
  json_txt = json_txt.replace(/\"/g , '').replace(/(^{)|(}$)/g , '');
  return json_txt;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my-element" data-request-data="bar: 1, foo: 2">

2 Comments

Thanks for your help :)
You're totally welcome @Duddy67 .. Have a nice day :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.