I am trying to use the node package jsbarcode
to generate barcodes. I need to be able to pass in variables from res.locals
into a file called main.js
which is in my public directory. Reason for this is that I need the barcodes to be generated on page load using data that is passed into the template using res.locals
html:
<img id="barcode"/>
main.js:
JsBarcode("#barcode", amodel + "-" + aNum, {
format: "CODE128C",
ean128: true
});
I am not sure the amodel + "-" + aNum
is even the correct format but essentially I need to be able to pass in a string then a -
then a number before generating the bar code. I would also like to be able to change the format of the bar code as well but that is not priority one.
TLDR:
How do I pass variable data into a client side js file?
I have solved this using a work around. I am sure there is a more "proper" way of doing it. Here is the html:
<style>
.hidden {display: none;}
<div id="test123" class="hidden">{{test}}</div>
<div id="codeType" class="hidden">{{codeType}}</div>
<img id="barcode"/>
Then the JS in a script tag on the same page:
<script>
var test = document.getElementById("test123").innerHTML;
var codeType = document.getElementById("codeType").innerHTML;
$('#barcode').JsBarcode('14374', {format: 'UPC'},{ width: 2, height: 90 });
</script>
Pretty much what this equates to is that I pass the res.locals into a hidden div then use .innerhtml
to extract the value into my variable. This works and I can load it 10/10 times no errors. I am using JSBarCode if anyone is wondering.