BOOKTHEPARTY
BOOKTHEPARTY

Reputation: 73

barcode generation in html using php giving same value

i am using js barcode generation to generate barcode in my PHP website, in the page I have multiple invoices and each one should have unique barcode, my code is like below:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>

<?php foreach($catil as $val){?>

<div class="col-4">
  <svg class="barcode"></svg>
  <script>
    JsBarcode(".barcode", "<?=$val->batchnumber?>");
  </script>

</div>

<?php}?>

however this is generating same barcode for all inoices even though the batchnumber column is unique for all the invoices, can anyone please tell me what is wrong in here, thanks in advance

Upvotes: 0

Views: 1856

Answers (2)

mplungjan
mplungjan

Reputation: 177885

Your element selector needs to be unique

Assuming batchnumber is unique You can fix it like this

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>

<?php 
foreach($catil as $val){
$batchnumber = $val->batchnumber;
?>

<div class="col-4">
  <svg id="B_<?=$batchnumber?>"></svg>
  <script>
    JsBarcode("#B_<?=$batchnumber?>", "<?=$batchnumber?>");
  </script>

</div>

<?php}?>

Upvotes: 1

You can do something like this:

I would add your barcode as a data attribute to the svg like,

<?php foreach($catil as $val){?>
<div class="col-4">
  <svg class="barcode" data-barcode="<?=$val->batchnumber?>"></svg>

</div>
<?php}?>

Then after all the bar codes has been generated then run this jquery code.

$(".barcode").each(function() {
  $(this).JsBarcode($(this).data("barcode"));
});

Demo

$(".barcode").each(function() {
  $(this).JsBarcode($(this).data("barcode"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jsbarcode/3.3.20/JsBarcode.all.min.js"></script>
<div class="col-4">
  <svg class="barcode" data-barcode="hi"></svg>

</div>
<div class="col-4">
  <svg class="barcode" data-barcode="test"></svg>

</div>

Upvotes: 2

Related Questions