Get value of each cell from dynamic table - javascript

I have dynamic table which is create like this
<table id="sort" class="table">
<thead>
<tr>
<th>Nazwa kolumny z BD*</th>
<th>Długość rekordu*</th>
<th>Nazwa kolumny wyświetlana</th>
<th>Format*</th>
</tr>
</thead>
<tbody id="tblsort">
#for (var i = 0; i < Model.listOfFormats(Model.field.TemplateName).ColumnNamesDB.Count; i++)
{
<tr>
<td>#Html.TextBoxFor(m => Model.listOfFormats(Model.field.TemplateName).ColumnNamesDB[i], new { #class = "form-control", })</td>
<td>#Html.TextBoxFor(m => Model.listOfFormats(Model.field.TemplateName).LengthColumns[i], new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(m => Model.listOfFormats(Model.field.TemplateName).ColumnNamesUser[i], new { #class = "form-control" })</td>
<td>#Html.DropDownListFor(m => Model.listOfFormats(Model.field.TemplateName).Formats[i], new SelectList(Model.formatFieldValues, "Value", "Text"), Model.listOfFormats(Model.field.TemplateName).Formats[i], new { #class = "form-control" })</td>
</tr>
}
</tbody>
</table>
How can I get value from each cel in this table? Thanks for help !
edit:
Ok I mean every cell data.
I tried your's solutions but nothing works
here is mine .html which is generate by browser
<tbody id="tblsort">
<tr>
<td name="cos"><input class="form-control" id="ColumnNamesDB_0_" name="ColumnNamesDB[0]" type="text" value="zzzz" /></td>
<td><input class="form-control" id="LengthColumns_0_" name="LengthColumns[0]" type="text" value="111" /></td>
<td><input class="form-control" id="ColumnNamesUser_0_" name="ColumnNamesUser[0]" type="text" value="zzzzz" /></td>
<td><select class="form-control" id="Formats_0_" name="Formats[0]"><option value=""></option>
<option value="DD-MM-YYY">DD-MM-YYY</option>
<option value="DDMMYYY">DDMMYYY</option>
<option value="NRB">NRB</option>
</select></td>
</tr>
</tbody>
When I run this code:
var value = $("#ColumnNamesDB[0]").attr('value');
var bla = $('.ColumnNamesDB_0_').val();
alert(bla);
alert(value);
I'm getting "undefined". Whats wrong?

I dont know what you mean by "value", but you can iterate over each <td> using jQuery each()
$(function() {
var myArray = [];
$('#tblsort td input').each(function() {
var input = $(this),
value = input.attr('value');
myArray.push(value);
});
console.log(myArray);
});

If what you mean is you want to grab ALL the cell's data. So you have to give the "name" attribute to each cell, and grab ALL the data using the name..
<td name="example[]"></td>
And you can grab it using the language you wanted (Jquery or PHP)..

Related

How do I add a class to a dynamic table's <td> element?

I have a dynamic table, where I need to sum up the values in a particular column, attaching an id property to each row would be the best way to achieve this. I'm only focused on setting and id for each <td> in every table row.
UPDATE: I have all 4 keys in the <td> but I would like each <td> to match what the value is.
JavaScript:
var prodArr = [];
data = [{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}];
function buildTable(data){
var table = document.getElementById('table');
const arr = data;
for(var obj of arr){
var row = document.createElement('tr');
row.setAttribute('id', Object.values(obj)[0]);
//redo this id stuff to maintain insert integrity for each column in the row.
for(var val of Object.values(obj)){
var col = document.createElement('td');
col.textContent = val;
row.appendChild(col);
col.setAttribute('class', Object.keys(obj));
}
var targetCell = row.getElementsByTagName("td");
targetCell[0].setAttribute('class', 'txtSku');
targetCell[1].setAttribute('class', 'txtRetailPrice');
targetCell[2].setAttribute('class', 'txtListPrice');
targetCell[3].setAttribute('class', 'txtProductName');
var input = document.createElement('input');
input.setAttribute('type', 'text');
//input.setAttribute('')
row.appendChild(input);
table.appendChild(row);
}
}
buildTable(data);
HTML:
<table id="table">
<tr>
<th><label>SKU:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal">
<input type="button" value= "Add" id = "addTotals">
</th>
</tfoot>
</table>
When complete I would like the html markup to look like this:
<table id="table">
<tr>
<td><input type="text" name="txtCustomerName" id = "txtCustomerName"></td>
<td><input type="text" name="txtPhone" id = "txtPhone"></td>
<td><input type="text" name="txtEmail" id= "txtEmail"></td>
<td><input type="text" name="txtRopo" id= "txtRopo"></td>
<td><input type="text" name="txtAddress" id= "txtAddress"></td>
</tr>
<tr>
<th><label>SKU:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td id="SKU">9372983-382L</td>
<td id="retailPrice">11.75</td>
<td id="listPrice">3.50</td>
<td id="prodName">Tennis balls</td>
<td id="quantity">1</td>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal">
<input type="button" value= "Add" id = "addTotals">
</th>
</tfoot>
</table>
https://codepen.io/Postman507/pen/mdrKZoY
try this
tr.id("id"+i)
It will not be possible to retrieve more than 1 element using ID. Use a class instead. To add just 1 class, you can use HTMLElement.className="class_name". To add more, you can use HTMLElement.classList.add("class_name")
the problem is really your data element. Try to do something like this:
data= {row1:{names:[],ids:[]},
row2:{labels:[]},
row3:{ids[]}}
obviously filling in the arrays with your data. Then in your js you can build your table and add classes and id's as needed.
The solution was using the tables properties to get the rows, then I was able to access the cell data using this outside of the last for loop but inside the first:
var targetCell = row.getElementsByTagName("td");
targetCell[0].setAttribute('class', 'txtSku');
targetCell[1].setAttribute('class', 'txtRetailPrice');
targetCell[2].setAttribute('class', 'txtListPrice');
targetCell[3].setAttribute('class', 'txtProductName');

Creating an array from table data and currently getting empty strings in the array

I have a table where the owner is meant to enter details:
<table id="ownerDetailsTable" style="margin-top: 20px; margin-bottom: 20px; width: 100%">
<thead>
<tr>
<td style="font-weight: bold">HP Point of Contact Name</td>
<td style="font-weight: bold">HP Point of Contact Title</td>
<td style="font-weight: bold">HP Point of contact email</td>
</tr>
</thead>
<tbody id="tableToModify">
<tr id="1">
<td>
#Html.TextBoxFor(m => m.InterventionOwnerName, new { #class = "form-control element-one", #maxlength = 250, placeholder = "Owner Name", value = "" })
</td>
<td>
#Html.TextBoxFor(m => m.InterverntionOwnerTitle, new { #class = "form-control element-two", #maxlength = 250, placeholder = "Owner Title", value = "" })
</td>
<td>
#Html.TextBoxFor(m => m.InterventionOwnerEmail, new { #class = "form-control element-three", #maxlength = 250, placeholder = "Owner Email", value = "" })
</td>
</tr>
</tbody>
</table>
<input id="addRow" , type="button" onclick="createRow(); getOwnerDetails()" value="Add Point of Contact" class="btn btn-primary" />
Currently, on click, a new row of inputs is created and the details entered by the user are meant to go into an array:
<script>
var ownerDetailArray = [];
function getOwnerDetails() {
$('table#ownerDetailsTable tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('input');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).text())
});
ownerDetailArray.push(arrayOfThisRow);
}
console.log(ownerDetailArray);
});
}
The array is being created but the strings in the array - which should be the info entered by the user - are empty. I feel as though the issue in the way that I am attempting to find the data and push it into the array. Any help/advice would be much appreciated!
If you are trying to get input value , then change arrayOfThisRow.push($(this).text()) to arrayOfThisRow.push($(this).val());
I assume your #Html.TextBoxFor creates <input /> tag.
var ownerDetailArray = [];
function getOwnerDetails() {
$('table#ownerDetailsTable tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('input');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).val());
});
ownerDetailArray.push(arrayOfThisRow);
}
console.log(ownerDetailArray);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="ownerDetailsTable" style="margin-top: 20px; margin-bottom: 20px; width: 100%">
<thead>
<tr>
<td style="font-weight: bold">HP Point of Contact Name</td>
<td style="font-weight: bold">HP Point of Contact Title</td>
<td style="font-weight: bold">HP Point of contact email</td>
</tr>
</thead>
<tbody id="tableToModify">
<tr id="1">
<td>
<input class = "form-control element-one", maxlength="250", placeholder = "Owner Name", value = ""/>
<#Html.TextBoxFor(m => m.InterventionOwnerName, new { #>class = "form-control element-one", #maxlength = 250, placeholder = "Owner Name", value = "" })
</td>
<td>
<input class = "form-control element-one", maxlength="250", placeholder = "Owner Name", value = ""/>
#Html.TextBoxFor(m => m.InterverntionOwnerTitle, new { #class = "form-control element-two", #maxlength = 250, placeholder = "Owner Title", value = "" })
</td>
<td>
<input class = "form-control element-one", maxlength="250", placeholder = "Owner Name", value = ""/>
#Html.TextBoxFor(m => m.InterventionOwnerEmail, new { #class = "form-control element-three", #maxlength = 250, placeholder = "Owner Email", value = "" })
</td>
</tr>
</tbody>
</table>
<input id="addRow" , type="button" onclick="getOwnerDetails()" value="Add Point of Contact" class="btn btn-primary" />

Ajax.BeginForm() Ajax Option Not Work in Razor View

Hi friend AjaxOption Not working in my Razor View
#using (Ajax.BeginForm("TestAvanceSearchRequisition", "Requisition",
new AjaxOptions
{
HttpMethod = "POST",
Confirm = "Do u Want to save",
UpdateTargetId = "divResponse"
}))
{
<table>
<tr>
<td class="lebelTD">
Date From:
</td>
<td class="fieldTD">
#Html.TextBox("requisition_from", "",
new
{
#class = "InputText",
onclick = "javascript:NewCssCal ('requisition_from','ddMMMyyyy','arrow','','','','')",
#style = "border-left:2px solid #FF3C3C;"
})
</td>
</tr>
<tr>
<td class="lebelTD">
Date To:
</td>
<td class="fieldTD">
#Html.TextBox("requisition_end_date", "",
new
{
#class = "InputText",
onclick = "javascript:NewCssCal ('requisition_end_date','ddMMMyyyy','arrow','','','','')",
#style = "border-left:2px solid #FF3C3C;"
})
</td>
</tr>
</table>
<table>
<tr>
<td align="right">
<input type="submit" class="smallbtn" />
</td>
</tr>
</table>
<div id="divResponse">
<table>
<tr>
<td class="lebelTD">Sales Total Amount</td>
<td class="fieldTD">
#Html.TextBox("Salesamt", #TempData["TotalSalesAmout"], new { #class = "InputText" })
</td>
</tr>
</table>
</div>
}
Not any Ajax Option not working. Like confirm box, Update Traget Id.. I had add all reference of Ajax.
Why not Ajax Option Not working. On button click go to Post method and get the result but no confirm box work and load full form.

How to make a number with commas as thousands separator in table, javascript

I want to print an integer with a comma as a separator, for example 10,234,234
in the price column.
I have made the function, but I am a little confused how to make it in the table. Below is my code
<table class="table">
<tr>
<th> Item</th>
<th>Price</th>
</tr>
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
<tr>
<td></td>
<td> #Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { #class = "form-control", #onchange = "validationCheck();", #readonly = "readonly" } }) </td>
</tr>
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
You need to get all second td elements in the table and then update the content using the code.
<table class="table" id="table">
<!-- set id to get table^^^^^^^^---->
<tr>
<th> Item</th>
<th>Price</th>
</tr>
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// get all second tds
[...document.querySelectorAll('#table tr > td:nth-child(2)')].forEach(e => {
// get text content and update
e.textContent = numberSeparator(e.textContent.trim());
})
</script>
FYI : It's always better to do it from the backend side if possible. There may be some functions available in your backend framework/programming language.
UPDATE : In your updated code you are creating an input so get input element update it's value.
<table class="table">
<tr>
<th> Item</th>
<th>Price</th>
</tr>
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
<tr>
<td></td>
<td> #Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { #class = "form-control", #onchange = "validationCheck();", #readonly = "readonly" } }) </td>
</tr>
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// get all second tds
[...document.querySelectorAll('#table tr > td:nth-child(2) input')].forEach(e => {
// get text content and update
e.value = numberSeparator(e.value.trim());
})
</script>
You can use toLocaleString to display a number with comma separators
let num = 1000000
let display = num.toLocaleString('us-US')
console.log(display) // 1,000,000
I suspect your code could work like this
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice.toLocaleString('us-US'))</td>
</tr>
}

Make a DIV show with jQuery in nested accordion structure

I have an accordion that is loaded from a model list, so it is repeated with new IDs assigned according to the ID of the model. In this structure I have a DIV is display:none and upon clicking a radio button I want it to slide down and show. This is some of my HTML:
<tr style="height:35px">
<td style="text-align:left" >
<label id="lblOtherAvery+#Model[i].UserId" style="font-size:x-small">Other:</label>
</td>
<td>
#Html.RadioButtonFor(x=>Model[i].AverySize, "Other", new { #id = "chkOtherAvery" + #Model[i].UserId, #style = "width:30px;", #class = "radLabel radLabelOther", #disabled = "disabled"})
</td>
</tr>
<tr>
<td style="text-align:center" colspan="2" >
<div id="divAvery_#Model[i].UserId" style="display:none;vertical-align:top;text-align:center" class="divAvery">
<table style="width:100%;text-align:center">
<tr style="height:20px;">
<td style="font-size:x-small">Rows:</td>
<td>#Html.TextBoxFor(x=>Model[i].LabelRows, new {#id = "txtRows" + #Model[i].Userd, style = "width:50px;font-size:x-small;height:20px"})<span style="font-size:x-small"><i>(MAX 16)</i></span></td>
<td style="font-size:x-small">Columns:</td>
<td>#Html.TextBoxFor(x=>Model[i].LabelColumns, new {#id = "txtColumns" + #Model[i].UserId, style = "width:50px;font-size:x-small;height:20px"})<span style="font-size:x-small"><i>(MAX 3)</i></span></td>
</tr>
</table>
</div>
</td>
</tr>
Then in the JS for when the radio is clicked:
$('.radLabelOther').on('click', function () {
var divId = $(this).closest('tr').next().children().find('.divAvery');
$(divid).slideDown().show();
});
But this doesn't work. I am able to get the DIV element OK, but I cannot get it to show. What am I doing wrong?
I have even tried to get the ID of the DIV with this:
var divId = $(this).closest('tr').next().children().find('.divAvery').attr('id');
But that doesn't work either.
I can get it to work now by doing this:
var $divId = $(this).closest('tr').next().children().find('.divAvery');
$divId.slideDown();
Why does that $ make it work?

Categories

Resources