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

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);
}
});
});
});

Related

Make a table row editable on click with Javascript

I want to make the row of my list editable after clicking on edit button. I set editablecontent= true for every row I want to change and added focus with onclick event but this works only for the first item. Could you suggest other ways of making the content of every row editable? I started recently to learn javascript so vanilla javascript would be better. Thanks!
Storedcontact = []
// Represent a contact
function convertToEntry(name, surname, phone, email) {
var obj = {
name: name,
surname: surname,
phone: phone,
email: email
};
return obj;
}
// add contacts
var form = document.getElementById("btn-submit");
form.addEventListener("click", function(ev) {
ev.preventDefault();
var name = document.getElementById("name").value;
var surname = document.getElementById("surname").value;
var number = document.getElementById("phone").value;
var mail = document.getElementById("email").value;
var duplicateFlag = false;
var entry = convertToEntry(name, surname, number, mail);
for (var i = 0; i < Storedcontact.length; i++) {
let entry = Storedcontact[i];
// this is duplicate
if (entry.name === name) {
alert("Duplicate") ;
duplicateFlag = true;
} else {
duplicateFlag = false;
}
}
// store and update ui onlz if name is not duplicate
if (duplicateFlag === false) {
Storedcontact.push(entry);
updateUI();
}
});
// showing contacts
function updateUI() {
var tbody = document.getElementById('entry-table');
// clearing the table
tbody.innerHTML = '';
var newHtml = '';
// looping the stored contacts
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable">${entry.name}</td>
<td contenteditable="true" id="editable">${entry.surname}</td>
<td contenteditable="true" id="editable">${entry.phone}</td>
<td contenteditable="true" id="editable">${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow();">Edit</button></td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
function checkDuplicate (name) {
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
if (entry.name === name) {
alert("Duplicate")
} else {
}
}
}
function editHtmlTableRow (){
document.getElementById("editable").focus();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min (3).css">
<title>MyAddressBook</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
My<span class="text-primary">Address</span>Book</h1>
<form id="address-form">
<div class="form-group"></div>
<label for="Name">Name</label>
<input type="text" id="name" class="form-control">
<div class="form-group"></div>
<label for="Surname">Surname</label>
<input type="text" id="surname" class="form-control">
<div class="form-group"></div>
<label for="Number">Number</label>
<input type="text" id="phone" class="form-control">
<div class="form-group"></div>
<label for="mail">E-mail</label>
<input type="text" id="email" class="form-control">
</div>
<br>
</br>
<input type="submit" value="Add contact" id="btn-submit" class="btn btn-primary btn-block container mt-4">
</form>
<table class="table table-striped">
<thread>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
<th>E-mail</th>
<th></th>
</tr>
</thread>
<tbody id="entry-table"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Assign a unique identifier such as your for loop counter to the Rows
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable"+i>${entry.name}</td>
<td contenteditable="true" id="editable"+i>${entry.surname}</td>
<td contenteditable="true" id="editable"+i>${entry.phone}</td>
<td contenteditable="true" id="editable"+i>${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow(${i});">Edit</button></td>
`;
tbody.appendChild(row);
}
and in your function
function editHtmlTableRow (i){
document.getElementById("editable"+i).focus();
}

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

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);
});

Align a dynamic thead and tbody - .Net MVC

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>

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