2

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

1 Answer 1

1

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

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

16 Comments

As i have to save say n number of barcodes in the array. So if i call the array var code = []; like this and in case of declaring id in html like id = "test[0]" and likewise . Is such declaration correct?
Your method of declaring the array as var code = ["Test", "Test2"]; is valid for limited set of entries but if i have about 15-20 then what should i do?
Javascript arrays accept any number of entry and of mixed types. Define it empty and add them later. You can test it here jsfiddle.net/BygmL/2
I declared the way you have told me but still I am getting the error.
i have first declared localStorage["counter"]=0; var code = ["Test", "Test2","Test3"]; localStorage.setItem("code", JSON.stringify(code));
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.