skip to Main Content

i want to change script data using javascript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
</head>
<body>
    <h1>Example</h1>
    <button id="loadData">Check</button>

    <button id="change">Change Data</button>

    <script id="datas">

data = {
    key: "ABCDEFG",
    balance: "100",
   }; // change this data using id
   
   </script>

   <script>

//    loadDataButton = document.getElementById("loadData");

document.getElementById("loadData").addEventListener("click", function () {

    alert(data.key);

});

document.getElementById("change").addEventListener("click", function () {

document.getElementById("datas").innerHTML = `data = {
    key: "BCSD123",
    balance: "200",
   };`;  // changed new data but till giving me key ABCDEFG

alert(data.key);

});
      </script>


</body>
</html>

this method change only for show but i click on check button than giving me old data .. this problem i am facing . i want data key after change script tag data BCSD123

2

Answers


  1. There’s no need to modify the contents of a <script> tag.

    • modify the data‘s key values using a new Proxy
    • preview the object internals setting a trap in the Setter of your proxy object
    • reflect the changes onto to target data object:
    // Some initial data:
    var data = { key: "SOM31D", balance: "0" }; 
    
    
    // Reflector:
    const react = (ob, cb, _r) => Object.assign(new Proxy(ob, {
      set: (...arg) => (_r = Reflect.set(...arg), cb?.(ob), _r)
    }), ob);
    
    // Use like:
    
    const previewData = (ob) => {
      document.querySelector("#previewData").value = JSON.stringify(ob, null, 2);
    };
    
    // Whenever `data` inits or changes, do something with that object:
    const dataProxy = react(data, previewData);
    
    document.querySelector("#loadData").addEventListener("click", function() {
      Object.assign(dataProxy, { key: "ABCDEFG", balance: "100" });
    });
    
    document.querySelector("#changeData").addEventListener("click", function() {
      Object.assign(dataProxy, { key: "BCSD123", balance: "200" });
    });
    <button id="loadData">Load data</button>
    <button id="changeData">Change data</button><br>
    <textarea rows=5 id="previewData"></textarea>
    Login or Signup to reply.
  2. I guess you want to change data’s value through dynamics, you can change the value of variable in the callback function.

    document.getElementById("change").addEventListener("click", function() {
      data.key = "BCSD123";
      alert(data.key);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search