navotera
navotera

Reputation: 321

Change Data Attribute json value

i want to change specific value of json array. for detail i have this dom :

<input class="fileupload" type="file" data-form-data='{"table_reference": "data_monitoring", "table_token" : "X43sd"}'>         

i know how to update the data attribute using jquery using this code : $(this).attr('key', 'value')

but how to change specific key in data attribute, for example on above dom I need to change the table_token value

thank for any suggestion

Upvotes: 1

Views: 2101

Answers (1)

guest271314
guest271314

Reputation: 1

You can use .data() with property reference to set the specific property to a value

$(".fileupload").data().formData.table_token = 123;

console.log($(".fileupload").data().formData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="fileupload" type="file" data-form-data='{"table_reference": "data_monitoring", "table_token" : "X43sd"}'>

If requirement is to set data-* which will be reflected in HTML you can use HTMLElement.dataset

var new_token = "abc";

let data = JSON.parse($(".fileupload")[0].dataset.formData);

data.table_token = new_token;

$(".fileupload")[0].dataset.formData = JSON.stringify(data);

Upvotes: 3

Related Questions