Raunak
Raunak

Reputation: 85

how to store values in an array

In the following code I am getting the scanned value of a barcode.

var scanCode = function () {
window.plugins.barcodeScanner.scan(function(result) {
    alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled);
    localStorage.setItem("myvalue1", result.text);
    window.location.href = 'page5.html';
    var barcodeVal = localStorage.getItem("myvalue1");
    var test2 = localStorage.getItem("code");
    code = JSON.parse(test2);
    var k = parseInt(localStorage.getItem("counter"));
    document.getElementById(code[k]).innerHTML = barcodeVal;
    alert(code[k]);
    alert(k);
    k++;
    localStorage["counter"] = k;
    localStorage.setItem("code", JSON.stringify(code));
}, function (error) {
    alert("Scan failed: " + error);
});

myvalue1 is the value i am getting from scanning . I have defined an array and a counter in another js file as

localStorage["counter"]=0;
var code = {};
localStorage.setItem("code", JSON.stringify(code));

Now i am trying to store the id in the array code[] and i am trying to print it in page5.html. Above <script> is also defined in the same page5.html. Also i am calling the scan function again and again to get multiple barcode scanned. I am printing the value in the html as

<tr>
    <td>2</td>
    <td id="code[0]"></td>
</tr>

I am getting the error as Cannot set property 'innerHTML' of null . What should i do next? Please help me. thanks in advance

Upvotes: 2

Views: 148

Answers (1)

Mauro
Mauro

Reputation: 2070

As you can see from the JsFiddle here when you do the code[k] in the instruction

document.getElementById(code[k]).innerHTML = barcodeVal;

code is not understood as an array of strings but as a string, so poining at code[0] it does not point to your id but to the bracket.

Do a JSON.parse() on your code as in the updated JsFiddle here

Upvotes: 1

Related Questions