In the example where I shared the code, I list the data in my model. I also generate barcode image with javascript from the barcode number that comes with the model. However, only the first result is producing a barcode image. The barcode image of other lines is empty. How do I make a change in Javascript?
@using BarcodeViewer.Models
@using System.Collections.Generic
@model List<PrintModel>
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML EAN13 Barcode</title>
<script src="~/js/connectcode-javascript-ean13.js"></script>
<style type="text/css">
#barcode {
font-weight: normal;
font-style: normal;
line-height: normal;
sans-serif;
font-size: 12pt
}
</style>
</head>
<body>
@foreach (var m in Model)
{
<div>
<table style="width:300px">
<tr>
<td></td>
<td></td>
<td><b>Tarih</b> </td>
<td>@m.Tarih.ToShortDateString()</td>
</tr>
<tr>
<td><b>Gönderen</b></td>
<td colspan="3">@m.Gonderen</td>
</tr>
<tr>
<td><b>Alıcı<b></td>
<td colspan="3">@m.Alici</td>
</tr>
<tr>
<td><b>İl</b></td>
<td>@m.City</td>
<td><b>İlçe</b></td>
<td>@m.Town</td>
</tr>
<tr>
<td><b>Miktar</b></td>
<td>@m.Quantity</td>
<td><b>Birim</b></td>
<td>@m.Birim</td>
</tr>
<tr>
<td><b>Stok Adı:</b></td>
<td colspan="3">@m.StokAdi</td>
</tr>
</table>
<div id="barcodecontainer" style="width:3in; align-content:flex-start" >
<div id="barcode">@m.Barcode</div>
</div>
</div>
<br />
}
<script type="text/javascript">
/* <![CDATA[ */
function get_object(id) {
var object = null;
if (document.layers) {
object = document.layers[id];
} else if (document.all) {
object = document.all[id];
} else if (document.getElementById) {
object = document.getElementById(id);
}
return object;
}
get_object("barcode").innerHTML = DrawHTMLBarcode_EAN13(get_object("barcode").innerHTML, "yes", "in", 0, 2.5, 1, "bottom", "center", "", "black", "white");
/* ]]> */
</script>
</body>
</html>
Because you are using an id
attribute for multiple elements. id
tags must be unique within the DOM. getElementById
will only return the first element with given id
.
Try using a class
instead of an id
and update your javascript code to "run for each element instance of class".
Don't use id attribute inside that loop. (id="barcodecontainer", id="barcode")
<div class="barcode"></div>
And js:
var barcodeElements = document.getElementsByClassName("barcode");
for(var i = 0; i < barcodeElements.length; i++) {
barcodeElements[i].innerHTML = DrawHTMLBarcode_EAN13(barcodeElements[i].innerHTML);
}
But you better use jQuery instead of this js code.
Lib for jQuery: https://barcode-coder.com/en/barcode-jquery-plugin-201.html
Here is usage for your code:
HTML:
<div class="barcode" data-code="@m.Barcode"></div>
JS:
$(".barcode").each(function(){
$(this).barcode($(this).attr('data-code'), "ean13");
});