Home > OS >  How to retrieve object from input value?
How to retrieve object from input value?

Time:09-16

I have this input field

<input type="hidden" class="tax_obj" value="[{" taxid":1,"taxname":"vat","taxpercentage":13,"sortorder":1,"calculationmode":null},{"taxid":2,"taxname":"hst","taxpercentage":10,"sortorder":2,"calculationmode":null}]">

How can I retrieve this object in javascript?

const input = document.querySelector('.tax_obj')
console.log(input.value)
    <title>Document</title>
  </head>
  <body>
    <form action="" class="try">
      <input type="text" class="tax_obj" value='[ {"taxid": 1, "taxname":
      "vat", "taxpercentage": 13, "sortorder": 1, "calculationmode": null }, {
      "taxid": 2, "taxname": "hst", "taxpercentage": 10, "sortorder": 2,
      "calculationmode": null }]'>
    </form>
  </body>
</html>

Here, the issue is your use of the "" and '' symbols. If you are using "" and you need to use another blockquote inside it, then you should use a single quote '' to get things working.

Afterwords, you can use a querySelector to grab the class and console its value.

CodePudding user response:

you need to use single quotes around the value, so the delimiter doesn't conflict with the quotes in the JSON.

<input type="hidden" class="tax_obj" value='[{" taxid":1,"taxname":"vat","taxpercentage":13,"sortorder":1,"calculationmode":null},{"taxid":2,"taxname":"hst","taxpercentage":10,"sortorder":2,"calculationmode":null}]'>

Then you can use JSON.parse() to parse the value.

let value = JSON.parse(document.querySelector(".tax_obj").value);

CodePudding user response:

Its looks like an array of object. This code may help you. If you want a specific object from this array. You can try value[0] or value[1]

<input id="input" type="hidden" class="tax_obj"
        value='[{"
        taxid":1,"taxname":"vat","taxpercentage":13,"sortorder":1,"calculationmode":null},{"taxid":2,"taxname":"hst","taxpercentage":10,"sortorder":2,"calculationmode":null}]'>
    <script>
        const value = document.getElementById('input').value;
        console.log(value);
    </script>
  • Related