Align a dynamic thead and tbody - .Net MVC - javascript

I'm try to align a table wich was generated by javascript, but I'already tried every thing and nothing work!
Note: I already try use display block on thead with text-align:center, already try to use display theader-goup too, align-text:center with a class for thead and th. But still doesn't work.
Can someone help me?
<div role="tabpanel" class="tab-pane" id="OrcamentoMaterial">
<div class="col-md-12">
<div class="page-header m-b-20" style="margin-top:-30px;">
<h2 class="m-b-10"><strong style="font-size:18px;">
<a style="color: red;">{{item.Codigo}} </a> - {{item.Descricao}}</strong></h2>
<div class="col-md-3">
<div class="fg-lin">
<label>Nome da pessoa que solicitou o orçamento</label>
<input id="txtPessoaSolicitouOrcamento" class="form-control fg-input" />
</div>
</div>
<div class="col-md-3" style="margin-top:-6px;">
<div class="fg-line">
<div class="select">
#Html.Label("Executor")
#Html.DropDownListFor(model => model.TecnicoId, Model.listaTecnicos, "Selecione", new { #id = "ddlPessoaExecutora", #style = "height:20px !important;", #class = "form-control " })
</div>
</div>
</div>
<div class="col-md-3">
<div class="fg-lin">
<label>Descrição</label>
<input id="txtDescricaoOrcamento" class="form-control fg-input" />
</div>
</div>
<div class="col-md-3">
<div class="fg-lin">
<label>Data orçamento</label>
<input type="datetime" id="txtDataOrcamento" class="form-control fg-input datepicker" />
</div>
</div>
</div>
<fieldset class="col-md-12 m-t-30 m-b-20">
<legend>ORÇAMENTO MATERIAL</legend>
<div class="row m-t-10">
<div class="form-group col-md-10 m-t-15">
<div class="fg-line">
<select id="selectMaterial" style="width:100%">
<text>
<option value="0" selected="selected"></option>
</text>
</select>
</div>
</div>
<div class="col-md-1 form-group fg-float m-t-10">
<div class="fg-line">
<label>Quantidade</label>
#Html.TextBoxFor(m => m.OrcamentoMaterial.QuantidadeMaterial, new { #class = "form-control fg-input", id = "txtMaterialQuantidade" })
</div>
#Html.ValidationMessageFor(o => o.Material.Nome, "", new { #class = "has-error text-danger" })
</div>
<div class="col-md-1">
<i class="zmdi zmdi-plus"></i>
</div>
</div>
<div class="row" style="font-size: smaller;">
</fieldset>
</div>
<table class="table table-striped" id="tableOrcamentoMaterial">
<thead align="center">
<tr>
<th>Material</th>
<th>Ni</th>
<th>Name</th>
<th>Qtd.</th>
<th>Value</th>
<th>Total</th>
</tr>
</thead>
<tbody class="tbFooterOrcamentoMaterial">
</tbody>
</table>
$("#btn-addOrcamentoMaterial").click(function ()
{
var solicitante = "";
var executor = "";
var descricaoOrcamento = "";
var TecnicoId = 0;
var dataOrcamento = "";
var material = "";
var qtdMaterial = "";
var valorTotal = 0;
var materialId = 0;
var codigoNi = "";
var codigoMaterial = "";
$("#ddlPessoaExecutora option:selected").val() != null ? TecnicoId = $("#ddlPessoaExecutora option:selected").val() : $("#ddlPessoaExecutora option:selected").val(0);
$("#txtPessoaSolicitouOrcamento").val() != null ? solicitante = $("#txtPessoaSolicitouOrcamento").val() : "Não informado";
$("#ddlPessoaExecutora option:selected").text() != "" ? executor = $("#ddlPessoaExecutora option:selected").text() : $("#ddlPessoaExecutora option:selected").val(1);
$("#txtDescricaoOrcamento").val() != null ? descricaoOrcamento = $("#txtDescricaoOrcamento").val() : "Não possui descrição";
$("#txtDataOrcamento").val() != null ? dataOrcamento = $("#txtDataOrcamento").val() : new Date();
$("#selectMaterial option:selected").text() != null ? material = $("#selectMaterial option:selected").text() : $("#selectMaterial option:selected").val(1);
$("#selectMaterial option:selected").val() != null ? materialId = $("#selectMaterial option:selected").val() : $("#selectMaterial option:selected").val(0);
$("#txtMaterialQuantidade").val() != null ? qtdMaterial = $("#txtMaterialQuantidade").val() : "0";
var qryMaterial = getMaterialbyId(materialId);
valor = qryMaterial.vlMaterial;
codigoNi = qryMaterial.CodigoNi;
codigoMaterial = qryMaterial.CodigoMaterial;
valorTotal = parseFloat(qtdMaterial) * valor;
var orcamentoExibir = codigoMaterial + "-" + codigoNi + "-" + material + "-" + qtdMaterial + "-" + valor + "-" + valorTotal;
orcamentoExibir = orcamentoExibir.split("-");
var orcamento = dataOrcamento + " - " + solicitante + " - " + executor + " - " + descricaoOrcamento + " - "+ codigoMaterial + "-" + codigoNi+ "-" + material + " - " + qtdMaterial + " - " + valor + " - " + valorTotal +" - " + TecnicoId +" - " + materialId;
incluirOrcamentoMaterial(orcamento, orcamentoExibir);
$("#ddlPessoaExecutora option:selected").val("");
$("#txtPessoaSolicitouOrcamento").val("");
$("#ddlPessoaExecutora option:selected").val(0);
$("#txtDescricaoOrcamento").val("");
$("#txtDataOrcamento").val("");
$("#selectMaterial option:selected").val(0);
$("#selectMaterial").text("");
$("#txtMaterialQuantidade").val("");
});
function incluirOrcamentoMaterial(orcamento, orcamentoExibir) {
listaOrcamentoMaterial.push(orcamento);
listaOrcamentoMaterialExibir.push(orcamentoExibir);
for (i = 0; i < listaOrcamentoMaterialExibir.length; i++) {
var tr = document.createElement('TR');
tr.class = 'rowOrcamentoMaterial';
i = listaOrcamentoMaterialExibir.length -1;
valorTotalOrcamento = valorTotalOrcamento + parseFloat(listaOrcamentoMaterialExibir[i][5]);
for (j = 0; j < listaOrcamentoMaterialExibir[i].length; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode(listaOrcamentoMaterialExibir[i][j]));
td.class = 'cellOrcamentoMaterial';
tr.appendChild(td)
}
$("#tableOrcamentoMaterial > tbody").append(tr);
}
$("#tableOrcamentoMaterial > tbody > tr").addClass("rowOrcamentoMaterial");
var tt = $(".rowOrcamentoMaterial").children.length;
debugger;
if(!$("#tableOrcamentoMaterial > tfoot .totalOrcamentoMaterial").html()){
$("#tableOrcamentoMaterial").append('<tfoot><tr><td colspan="5"></td><td class="totalOrcamentoMaterial orcamento" style="color:red;">'+ valorTotalOrcamento + '</td></tr></tfoot>');
} else
{
$("#tableOrcamentoMaterial > tfoot .totalOrcamentoMaterial").html(valorTotalOrcamento);
}
};

Put the table on a div element, then give the div a width and a margin for example
<div id="styleExample" style="width:920px; margin:auto">
<table id="yourTable"...></table>
</div>

Related

How to have a live data from localStorage with javascript

I have a cart list of customer shopping
I save customer items with add to basket button to localStorage
I have 2 problems
First one my data of basket in page is old and need to updated without refresh page
Second in a quick show of my basket at the top repeat the old data with add to basket button every time
Its quick view of the basket
function quickCartShow() {
let basketNumber = document.getElementById("card-value-numbers");
let cartItemsList = $("#cart-item-list");
let quickCart;
let price = 0;
basketNumber.innerText = cartItems ? cartItems.length : 0 ;
cartItems && cartItems.map(item => {
quickCart =
`<div class="row m-0 border-bottom mb-1"><div class="col-4 p-0 pl-1 align-self-center"> <a class="w-100" href="#` +
item.product.url +
`"> <img draggable="false" class="w-100" src="#` +
item.product.mainpic +
`" alt="product img"></a></div><div class="col-8 p-0"><div><a class="w-100 text-muted cart-text" href="#` +
item.product.url +
`"><p>` +
item.product.title +
`</p></a></div> <div class="d-flex justify-content-between"><p class="text-muted"> ` +
item.quantity +
// TODO: Active delete part here
` عدد </p><a class="pl-3 text-muted del-btn" onclick="removeFromCartHandler(this)"><i class="fas fa-trash-alt"></i></a></div> </div></div>`;
let advancePrice;
if (item.length) {
advancePrice = item.quantity * item.length
item.product.advance_prices.map(adPrice =>{
advancePrice <= adPrice.max ? price += advancePrice * adPrice.vprice : price +=0
})
} else {
item.product.offtype == 0 ? price += (item.quantity * item.product.price) :
item.product.offtype == 1 ? price += (item.quantity * (((100-item.product.off)/100)*item.product.price)) :
item.product.offtype == 2 ? price += ((item.quantity * item.product.price) - item.product.off) : price+= 0;
}
$("#cart-value-price").text(numberWithCommas(price));
cartItemsList.append(quickCart);
});
}
and the basket part code is:
function cardItemsShow() {
let cartContainer = $('.cart-items-page');
let questPrice = $('#guest-prices');
let cartItemShow;
let price = 0;
let cartsItemParent = $('.cart-items-page');
cartsItemParent.find("tr").remove();
cartItems && cartItems.map((item,i) => {
var maxProduct = ((item.product.max && ( item.product.instock != 2 || (item.product.max < item.product.stock)))) ?
item.product.max : item.product.instock == 2 ? item.product.stock : null
console.log(item)
cartItemShow =
`<tr class="class='col-12 checkout-item">`+
`<td>`+
`<a href="#`
+ item.product.url +
`">` +
`<img draggable="false" src="#` +
item.product.mainpic +
`" alt"`
+ item.product.title +
`">` +
`</a>` +
`</td>` +
`<td class="text-right">`+
`<a class="text-muted" style="display: inline-block" href="#` + item.product.url +
`">` + item.product.title +
`</a></td>` +
`<td>
<span style="white-space: nowrap"> `
+
((item.length !== null) ? item.length + ' سانتی متر '
: '')
+
`</span>
</td>
<td>
<div>
<form class="`+item.id+ ` onsubmit="return false" >
<p class="mb-0">تعداد</p>
<div class="number-input">
<button
onclick="this.parentNode.querySelector('input[type=number]').stepDown(); $('#refresh-btn`+i+`').removeClass('d-none')" type="button"></button>
<input class="quantity number-picker" min="0" name="quantity" id="quantity" max="`+ maxProduct +`"
value="`+ item.quantity+`" type="number">
<button
onclick="this.parentNode.querySelector('input[type=number]').stepUp(); $('#refresh-btn`+i+`').removeClass('d-none')"
class="plus" type="button"></button>
</div>
<div class="pt-1">
<a class="btn btn-success refresh-btn d-none" id="refresh-btn`+i+`" href="#" onclick="updateCartShow()" >
<i class="fas fa-sync-alt"></i>
<span> به‌روزرسانی</span>
<a/>
</form>
</div>
</div>
</td>
<td><spam>` +
numberWithCommas(item.product.price)
+
`
تومان
</spam>
</td>
<td>
<button onclick="removeFromCartHandler()" class="checkout-btn-remove remove-cart"> × </button>
</td>
</tr> `
cartContainer.append(cartItemShow)
let advancePrice;
if (item.length) {
advancePrice = item.quantity * item.length
item.product.advance_prices.map(adPrice =>{
advancePrice <= adPrice.max ? price += advancePrice * adPrice.vprice : price +=0
})
} else {
item.product.offtype == 0 ? price += (item.quantity * item.product.price) :
item.product.offtype == 1 ? price += (item.quantity * (((100 - item.product.off)/100)*item.product.price)) :
item.product.offtype == 2 ? price += ((item.quantity * item.product.price) - item.product.off) : price+= 0;
}
questPrice.text(numberWithCommas(price))
})
}
function updateCartShow() {
cardItemsShow();
quickCartShow();
}
updateCartShow()
document.addEventListener("visibilitychange", event => {
if (document.visibilityState === "visible") {
updateCartShow();
}
});
$(document).on("click", ".add-to-basket", function() {
console.log("aaaa");
updateCartShow();
});
});
Thanks for your help

MVC VB.NET webpage with Javascript Dynamic created table save to sql

first post here, I've being developing sites for some time using MVC and VB.NET but currently I have a request to create or add dynamically lines to a table and store or save this data into a table. I am working with the following to create this. please notice that the site has to parts, the first part contains the static values that are stored in another table but related to the table that is stored in another table. Any help will be appreciated.
The below code controls the "post" button and I want to go through all columns and rows, save them as an array then post it a table in SQL and I will take it from there, but the code below does nothing. Take in consideration that I need the fields "open" for edit in all rows until the "post" button is hit.
``
("#buttonPost").on("click", function () {
var tbl = document.getElementById('tblEventPrices');
var rCount = tbl.rows.length;
//try {
// alert(tbl.rows[rCount - 1].cells[0].children[0].value);
// alert(tbl.rows[rCount - 2].cells[0].children[0].value);
// alert(rCount);
// //alert(tbl.rows[rCount - 1].cells[1].children[0].value);
//} catch (e) {
// alert(e);
//}
//var table = document.getElementById("mytab1");
//for (var i = 0, row; row = tbl.rows[i]; i++) {
// //iterate through rows
// //rows would be accessed using the "row" variable assigned in the for loop
// for (var j = 0, col; col = row.cells[j]; j++) {
// //iterate through columns
// //columns would be accessed using the "col" variable assigned in the for loop
// alert(tbl.rows[i].cells[j].children[0].value);
// }
//}
//for (var i = 0 ; i < tbl.rows.length; i++) {
// var row = "";
// for (var j = 0; j < tbl.rows[i].cells.length; j++) {
// row += tbl.rows[i].cells[j].children[0].value;
// row += " | ";
// }
// alert(row);
//};
//var table = document.getElementById("mytab1");
for (var i = 0, row; row = tbl.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
alert(tbl.rows[i].cells[j].children[0].value)
}
}
alert(tbl.rows[1].cells[0].children[0].value);
alert(tbl.rows[rCount - 1].cells[0].children[0].value);
//});
});
`
Full Code Below
#ModelType EventsModel
#Code
ViewData("Title") = "Crear Evento"
Layout = "~/Views/Shared/_Layout.vbhtml"
ViewBag.Title = "Crear Evento"
End Code
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<h2>#ViewBag.Title</h2>
<hr />
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<section id="UpdateEventForm">
#Using Html.BeginForm("Create", "Events", New With {.ReturnUrl = ViewBag.ReturnUrl}, FormMethod.Post, New With {.enctype = "multipart/form-data", .class = "form-horizontal", .role = "form"})
#Html.AntiForgeryToken()
#<text>
#Html.ValidationSummary(True, "", New With {.class = "text-danger"})
<div class="col-sm-12 col-md-12 col-lg-12">
<div Class="form-group">
#Html.ActionLink("Crear Marca", "BrandCreate", "Events")
<br />
#Html.LabelFor(Function(m) m.Brand_Name, New With {.class = "col-md-4 control-label"})
<div Class="col-md-offset-4 ">
#Html.DropDownListFor(Function(m) m.Brand_ID, New SelectList(Model.EventsDataList_Brand, "Brand_ID", "Brand_Name"), "Marca...", New With {.Class = "form-control"})
#Html.ValidationMessageFor(Function(m) m.Brand_ID, "", New With {.Class = "text-danger"})
</div>
</div>
<div Class="form-group">
#Html.LabelFor(Function(m) m.EventCategoryName, New With {.class = "col-md-4 control-label"})
<div Class="col-md-offset-4 ">
#Html.DropDownListFor(Function(m) m.Category_ID, New SelectList(Model.EventsDataList_Category, "Category_ID", "EventCategoryName"), "Categoría...", New With {.Class = "form-control"})
#Html.ValidationMessageFor(Function(m) m.Category_ID, "", New With {.Class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(Function(m) m.Event_Name, New With {.class = "col-md-6 control-label"})
<div Class="col-md-offset-4 ">
#Html.TextBoxFor(Function(m) m.Event_Name, New With {.placeholder = "Nombre del Evento", .class = "form-control", .style = "padding: 10px; border-bottom: 0.7px solid;border-Left: 0.7px solid; border-bottom-left-radius: 15px;"})
#Html.ValidationMessageFor(Function(m) m.Event_Name, "", New With {.class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(Function(m) m.Event_Description, New With {.class = "col-md-6 control-label"})
<div Class="col-md-offset-4 ">
#Html.TextAreaFor(Function(m) m.Event_Description, New With {.placeholder = "Detalles del Evento", .class = "form-control input-lg textarea-editor PETextEditor", .TextMode = "MultiLine", .rows = "5", .style = "padding: 10px; border-bottom: 0.7px solid;border-Left: 0.7px solid; border-bottom-left-radius: 15px;"})
#Html.ValidationMessageFor(Function(m) m.Event_Description, "", New With {.class = "text-danger"})
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(Function(m) m.Event_Short_Description, New With {.class = "col-md-8 control-label"})
<div Class="col-md-offset-6 ">
#Html.TextAreaFor(Function(m) m.Event_Short_Description, New With {.placeholder = "Descripción del Evento", .rows = "5", .class = "form-control", .style = "padding: 10px; border-bottom: 0.7px solid;border-Left: 0.7px solid; border-bottom-left-radius: 15px;width:800;"})
#Html.ValidationMessageFor(Function(m) m.Event_Short_Description, "", New With {.class = "text-danger"})
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(Function(m) m.Event_Date_Start, New With {.class = "col-md-6 control-label"})
<div Class="col-md-offset-4 ">
#Html.EditorFor(Function(m) m.Event_Date_Start, New With {.class = "form-control", .style = "padding: 10px; border-bottom: 0.7px solid;border-Left: 0.7px solid; border-bottom-left-radius: 15px;"})
#Html.ValidationMessageFor(Function(m) m.Event_Description, "", New With {.class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(Function(m) m.Event_Date_End, New With {.class = "col-md-6 control-label"})
<div Class="col-md-offset-4 ">
#Html.EditorFor(Function(m) m.Event_Date_End, New With {.class = "form-control", .style = "padding: 10px; border-bottom: 0.7px solid;border-Left: 0.7px solid; border-bottom-left-radius: 15px;"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(Function(m) m.Is_Full_Day, New With {.class = "col-md-6 control-label"})
<div Class="col-md-offset-4 ">
#Html.EditorFor(Function(m) m.Is_Full_Day, New With {.class = "form-control", .style = "padding: 10px; border-bottom: 0.7px solid;border-Left: 0.7px solid; border-bottom-left-radius: 15px;"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(Function(m) m.Event_Poster_File, New With {.class = "control-label col-md-8"})
<div Class="col-md-offset-4 ">
#Html.TextBoxFor(Function(m) m.Event_Poster_File, New With {.type = "file", .aria_describedby = "fileHelp", .Class = "form-control-file"})
<small id="fileHelp" Class="form-text text-muted">Poster o imagen del evento</small>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-center">
<input type="button" id="StartButton" value="Agregar Tipo de Boleto" class="btn btn-outline-primary" onclick="GeneralPrice()" />
<input id="AddRowButtom" type="button" class="btn btn-outline-primary" value="Add Row"/>
#*<input type="button" id="StartButton" value="Boleto de Cortesía" c#*lass="btn btn-outline-primary" onclick="GiftPrice()" />
<input type="button" id="StartButton" value="Donación" class="btn btn-outline-primary" onclick="PromoPrice()" />*#
</div>
</div>
<table id="tblEventPrices" class="table table-condensed table-hover">
<thead>
<tr>
#*<th>
#Html.DisplayNameFor(Function(m) m.Price_Name)
</th>*#
<th>
#Html.DisplayNameFor(Function(m) m.Event_Price_Description)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Price)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Price_Qty)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Tax_1)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Tax_2)
</th>
#*<th><input type="button" id="btnAdd" value="Agregar" /></th>*#
<th></th>
</tr>
</thead>
<tbody>
#code dim i As Int32 = 1 end code
#If (Model.EventsDetails IsNot Nothing) Then
#For Each item In Model.EventsDetails.ToList()
#<tr>
#*<td>
#Html.EditorFor(Function(m) m.EventsDetails(i).Price_Name, New With {.id = "txtPriceName_" + i})
</td>*#
<td>
#Html.EditorFor(Function(m) m.EventsDetails(i).Event_Price_Description, New With {.id = "txtPriceDescription_" + i})
</td>
<td>
#Html.EditorFor(Function(m) m.EventsDetails(i).Event_Price, New With {.id = "txtPrice_" + i})
</td>
<td>
#Html.EditorFor(Function(m) m.EventsDetails(i).Event_Price_Qty, New With {.id = "txtPriceQty_" + i})
</td>
<td>
#Html.EditorFor(Function(m) m.EventsDetails(i).Event_Tax_1, New With {.id = "txtTax1_" + i})
</td>
<td>
#Html.EditorFor(Function(m) m.EventsDetails(i).Event_Tax_2, New With {.id = "txtTax2_" + i})
</td>
<td><input type="button" value="Borrar" onclick="Remove(this)" /></td>
</tr>
#code i = i + 1 end code
Next
End If
</tbody>
</table>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnSavePublish" value="Publicar" formaction="CreateSubmitPublish" formmethod="post" class="btn btn-outline-primary" name="SubmitPublish" />
<input type="submit" id="btnSave" value="Guardar" formaction="EventCreate" formmethod="post" class="btn btn-outline-primary" name="CreateEvent" />
#*<input type="submit" id="btnSaveSubmitPreview" value="Guardar y Vista Previa" formaction="#Url.Action("CreateSubmitPreview")" class="btn btn-outline-primary" name="SubmitPreview" />*#
<input type="button" id="btnSaveSubmitPreview" value="Guardar y Vista Previa" class="btn btn-outline-primary" name="SubmitPreview" />
<input id="buttonPost" type="button" class="btn btn-outline-primary" value="Postar" />
#*<input type="submit" value="Crear" formaction="PricesSubmitDetails" class="btn btn-outline-primary" name="submitDetails" />*#
</div>
</div>
</div>
</text>
End Using
</section>
</div>
</div>
</div>
#Section Scripts
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript" src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({ menubar: false, mode: 'specific_textareas', width: 800, editor_selector: 'PETextEditor', theme: 'modern' });
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#AddRowButtom").on("click", function () {
var table = document.getElementById('tblEventPrices');
var nextIndex = table.childNodes.length;
var htmlLbl = '<tr><td><input type="text" id="txtPriceDescription"/></td><td><input type="number" id="txtPrice" min="1" /></td><td><input type="number" id="txtPriceQty" min="1" /></td><td><input type="checkbox" id="txtTax1" /></td><td><input type="checkbox" id="txtTax2" /></td><td><input type="button" value="Borrar" onclick="Remove(this)" /></td></tr>';
table.insertRow(-1).innerHTML = htmlLbl
});
$("#buttonPost").on("click", function () {
var tbl = document.getElementById('tblEventPrices');
var rCount = tbl.rows.length;
//try {
// alert(tbl.rows[rCount - 1].cells[0].children[0].value);
// alert(tbl.rows[rCount - 2].cells[0].children[0].value);
// alert(rCount);
// //alert(tbl.rows[rCount - 1].cells[1].children[0].value);
//} catch (e) {
// alert(e);
//}
//var table = document.getElementById("mytab1");
//for (var i = 0, row; row = tbl.rows[i]; i++) {
// //iterate through rows
// //rows would be accessed using the "row" variable assigned in the for loop
// for (var j = 0, col; col = row.cells[j]; j++) {
// //iterate through columns
// //columns would be accessed using the "col" variable assigned in the for loop
// alert(tbl.rows[i].cells[j].children[0].value);
// }
//}
//for (var i = 0 ; i < tbl.rows.length; i++) {
// var row = "";
// for (var j = 0; j < tbl.rows[i].cells.length; j++) {
// row += tbl.rows[i].cells[j].children[0].value;
// row += " | ";
// }
// alert(row);
//};
//var table = document.getElementById("mytab1");
for (var i = 0, row; row = tbl.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
alert(tbl.rows[i].cells[j].children[0].value)
}
}
alert(tbl.rows[1].cells[0].children[0].value);
alert(tbl.rows[rCount - 1].cells[0].children[0].value);
//});
});
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
//if (confirm("Estás seguro de borrar: " + name)) {
if (confirm("Estás seguro de borrar")) {
//Get the reference of the Table.
var table = $("#tblEventPrices")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
</script>
End Section
</body>
If anyone is having this issue below the code, the issue is that each row had the same "id", although this was answer in another question, the difference is that this page that I have built each line is editable, so the way to access the table data is a little different, this cost me 20 bucks but hope to help somebody else.
Below how the table gets loaded
<table id="tblEventPrices" class="table table-condensed table-hover">
<thead>
<tr>
#*<th>
#Html.DisplayNameFor(Function(m) m.Price_Name)
</th>*#
<th>
#Html.DisplayNameFor(Function(m) m.Event_Price_Description)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Price)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Price_Qty)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Tax_1)
</th>
<th>
#Html.DisplayNameFor(Function(m) m.Event_Tax_2)
</th>
#*<th><input type="button" id="btnAdd" value="Agregar" /></th>*#
<th></th>
</tr>
</thead>
<tbody id="tblEventPricesbody"></tbody>
</table>
And this is the javascript
<script type="text/javascript">
$(document).ready(function () {
$("#AddRowButtom").on("click", function () {
var table = document.getElementById('tblEventPrices');
var tbodyRowCount = table.tBodies[0].rows.length;
var rowId = tbodyRowCount + 1;
var last_id = $('#tblEventPricesbody tr:last').attr('id');
if (rowId == last_id) {
rowId = rowId + 1;
}
//alert(rowId);
var htmlLbl = '<tr id="' + rowId + '"><td><input type="text" id="txtPriceDescription_' + rowId + '"/></td><td><input type="number" id="txtPrice_' + rowId + '" min="1" /></td><td><input type="number" id="txtPriceQty_' + rowId + '" min="1" /></td><td><input type="checkbox" id="txtTax1_' + rowId + '" /></td><td><input type="checkbox" id="txtTax2_' + rowId + '" /></td><td><input type="button" value="Borrar" onclick="Remove(' + rowId + ')" /></td></tr>';
$("#tblEventPricesbody").append(htmlLbl);
});
$("#buttonPost").on("click", function () {
var EvDesc = '';
var EvPrice = '';
var EvQTY = '';
var EvTax1 = '';
var EvTax2 = '';
var trid = '';
var userName = '#HttpContext.Current.User.Identity.Name';
var EventPrices = new Array();
var BrandId = $("#BrandId").val();
var CategoryID = $("#CategoryId").val();
var EventName = $("#EventName").val();
var EventDescription = tinyMCE.activeEditor.getContent();
var EventFacebook = $("#EventFacebook").val();
var EventInstagram = $("#EventInstagram").val();
var EventTwitter = $("#EventTwitter").val();
var EventPersonalizedUrl = $("#EventPersonalizedUrl").val();
var EventDateStart = $("#Event_Date_Start").val();
var EventDateEnd = $("#Event_Date_End").val();
var IsFullDay = $("#Is_Full_Day").is(":checked");
var EventPosterFile = $("#EventPosterFile").val();
var priceData = {};
priceData.Brand_Id = BrandId;
priceData.Category_ID = CategoryID;
priceData.Event_Name = EventName;
priceData.Event_Description = EventDescription;
priceData.Event_Facebook = EventFacebook;
priceData.Event_Instagram = EventInstagram;
priceData.Event_Twitter = EventTwitter;
priceData.Event_Personalized_Url = EventPersonalizedUrl;
priceData.Event_Date_Start = EventDateStart;
priceData.Event_Date_End = EventDateEnd;
priceData.Is_Full_Day = IsFullDay;
priceData.Event_Poster_File = EventPosterFile;
EventPrices.push(priceData);
$("#tblEventPricesbody tr").each(function () {
trid = this.id;
var price = {};
price.EvDesc = $("#txtPriceDescription_" + trid).val();
price.EvPrice = $("#txtPrice_" + trid).val();
price.EvQTY = $("#txtPriceQty_" + trid).val();
price.EvTax1 = $("#txtTax1_" + trid).is(":checked");
price.EvTax2 = $("#txtTax2_" + trid).is(":checked");
price.userName = userName
EventPrices.push(price);
//alert(EvDesc + "|" + EvPrice + "|" + EvQTY + "|" + EvTax1 + "|" + EvTax2 + "|" + trid);
});
alert(JSON.stringify(EventPrices))
$.ajax({
type: 'POST',
url: "#Url.Action("PricesTemp")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify(EventPrices),
success: function (data) {
console.log(data);
}
});
});
});

Send the value of javascript variable to html

I am unable to send the value of javascript variale 'userResults' to .html.
I want to display the contents of the form in tabular form.
Can you tell me a workaround for this?
This is in index.html
<form onSubmit="App.retrieveTransaction();" class="form2">
<h1 class="text-center">Retrieve transactions</h1>
<div class="form-group">
<label for="enterregnoselect">Reg No:</label><input id ="enterregnoselect" class="form-control" type ="text" required/>
</div>
<button type="submit" class="btn btn-primary" >Retrieve</button>
<hr />
<table class="table">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Name</th>
<th scope="col">Item</th>
<th scope="col">Credit</th>
<th scope="col">Debit</th>
<th scope="col">Price</th>
<th scope="col">Qty</th>
</tr>
</thead>
<tbody id="userResults">
</tbody>
</table>
<hr/>
</form>
This is the retrieveTransaction function in app.js called on submitting the form in index.html
retrieveTransaction: function() {
var transactionInstance;
var enteredregno = $('#enterregnoselect').val();
// var enteredregno = "0015/55";
App.contracts.Payment.deployed().then(function(instance) {
transactionInstance = instance;
return transactionInstance.transactionCount();
}).then(function(transactionCount) {
var userResults = $("#userResults");
userResults.empty();
for (var i = 1; i <= transactionCount; i++) {
transactionInstance.transactions(i).then(function(transaction) {
var date = transaction[0];
var regno = transaction[1];
var name = transaction[2];
var item = transaction[3];
var credit = transaction[4];
var debit = transaction[5];
var price = transaction[6];
var qty = transaction[7];
if(enteredregno == regno) {
var userTemplate = "<tr><th>" + date + "</th><td>" + name + "</td><td>" + item + "</td></tr>" + credit + "</th><td>" + debit + "</td><td>" + price + "</td></tr>" + qty + "</td></tr>";
userResults.append(userTemplate);
}
});
}
});

How to find the closest table row using jQuery?

I have problem getting the value of the replace new table row, I will let you show the codes for the replacing new table row.
The is the Table B, Where this code use for replacing new table row to the Table A
$('#edit_chainingBuild').on('click','tr.clickable-row',function(e){
$('table#edit_chainingBuild tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_will_update = $(this).find('.data-attribute-chain-id').attr('data-attribute-chain-id');
$('.id_to_update_chain').val(find_each_id_will_update);
var find_each_id_condiments = $(this).find('.data-attribute-chain-id').attr('data-attribute-condiments-section-id');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var condiment_section_name = stringify['condiment_section_name'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#edit_table_chaining_condiments').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td>"+condiment_section_name +"</td><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
$("table#edit_table_chaining_condiments tr").click(function(e){
var tableBhtml = $(this).closest('tr').html();
var condiments_name = $(this).closest("tr").find(".edit_condimentsScreenNameClicked").text();
var condimentsScreenPriced = $(this).closest("tr").find(".edit_condimentsScreenPriced").text();
// var input = '<input type="number" id="qty" name="qty" class="form-control changeQuantity" value="1" min="1">';
var id_to_edit_build = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").html('');
var id_to_edit_builders = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").replaceWith("<tr data-attribute-chain-id=" + id_to_edit_build + " class='clickable-row'><td class='new_condiments_name'>"+condiments_name+"</td><td>"+condimentsScreenPriced+"</td><td style='display:none;' data-attribute-chain-id="+id_to_edit_builders +" class='data-attribute-chain-id'>"+id_to_edit_builders+"</td></tr>");
$('#EditcondimentsBuilderModal').modal('hide');
});
},
error:function(response){
console.log(response);
}
});
$('#EditcondimentsBuilderModal').modal('show');
});
Looking forward if the table row already replace, I want to get the value of the class of new_condiments_name. So I create a variable to find the class of new_condiments_name. It look like this.
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
So now when I try alert the variable new_condiments_name using the click function it shows null only.
$('.edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
My Html Table:
<div class="modal-body">
<div class="container">
<div class="header" style="text-align: center;">
<br>
<h3 style="color:#007BFF;">Build Your Chain Button</h3>
<label>This button will be served as customers menu.</label><br>
<i class="fab fa-creative-commons-remix" style="font-size:70px;"></i>
<br><br>
<input type="hidden" value="" class="edit_hidden_noun_id" name="">
<table class="table table-hover" id="edit_chainingBuild">
<thead>
<tr style="font-size: 15px;">
<!-- <th scope="col">Qty</th> -->
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px;">
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="edit_build_success_insert btn btn-primary">Build Done</button>
</div>
I have here the image to proof that the value that i get always null.
$('table .edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});

how to find total value from adding value in html and value in dynamic form with javascript?

i have problem to find total_penjualan value.
i use dynamic form here. i want add all total's value in dynamic form with biayalainlain's value. i think the problem is in var ttl2 = document.getElementById(totalid).value; how to get id in additem() to put in prosestotal()?
this is my html and javascript code:
function sum() {
var hrg = document.getElementById('harga').value;
var jml = document.getElementById('jumlah').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
/*nama_input.setAttribute('id', 'nama');*/
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
/* kode_input.setAttribute('id', 'kode1');*/
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('type', 'number');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'harga form-control');
/*harga_input.setAttribute('onkeyup', 'sum();');*/
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('type', 'number');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'jumlah form-control');
jumlah_input.setAttribute('autocomplete', 'off');
/*jumlah_input.setAttribute('onkeyup', 'sum();');*/
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'total form-control');
total_input.setAttribute('readonly', '');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
$(jumlah_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(harga_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(total_input).on('keyup',function(){
prosestotal(totalid,total,biayalain)
})
function sum(hargaid,jumlahid,totalid) {
var hrg = document.getElementById(hargaid).value;
var jml = document.getElementById(jumlahid).value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById(totalid).value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
}
function prosestotal(){
var ttl = document.getElementById('total').value;
var ttl2 = document.getElementById(totalid).value;
var biayalain = document.getElementById('biayalain').value;
var hsl = parseInt(ttl) + parseInt(ttl2) + parseInt(biayalain);
if (!isNaN(hsl)) {
document.getElementById('total_penjualan').value = hsl;
}
}
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input type="number" id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input type="number" id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value="" onkeyup="prosestotal();" /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" id="tambah" class="btn btn-default">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
<!-- Baris biaya lain-lain -->
<div style="padding-top: 10px; padding-bottom: 15px;" class="col-lg-10">
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<label class="col-sm-6 control-label"><b>Biaya Lain-lain :</b></label>
</div>
</div>
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<input id="biayalain" type="number" autocomplete="off" class="form-control" name="biaya_lainlain" value="" onkeyup="prosestotal();">
</div>
</div>
</div>
<!-- baris biaya dan lain-lain end -->
<div style="padding-top: 10px; padding-bottom: 15px;" class="col-lg-10">
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<label class="col-sm-6 control-label"><b>Total Penjualan :</b></label>
</div>
</div>
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<input id="total_penjualan" type="number" readonly autocomplete="off" class="form-control" name="total_penjualan" value="" onkeyup="prosestotal();">
</div>
</div>
</div>
any help is appreciated

Categories

Resources