Getting Data in vb.net from dynamic htmlTable - javascript

I have a html table that I'm running at the server level. However, I'm having trouble accessing the data that it is being populated with.
I'm populating the table using javascript but I need to access the data using vb.net.
I'm using jquery to get the information to the page by using the .html method.
Here is my javascript,
function ShowProj(strId, qno,ar) {
$('#hiddenQno').val(qno);
$('#qnoLbl').val(qno);
var output = '';
output = "<tr><th>Product</th>";
output += "<th>Bond</th>";
output += "<th>Cut</th>";
output += "<th>Pack</th>";
output += "<th>Delivery date</th></tr>";
for (i = 0; i < ar.length; i++) {
output += "<tr>";
output += "<td style='width: 40%;'>" + ar[i][0] + "</td>";
output += "<td style='width: 10%; text-align: center;'><input type='checkbox' " + (ar[i][1] == 1 ? 'checked' : '') + " /></td>";
output += "<td style='width: 10%; text-align: center;'><input type='checkbox' " + (ar[i][2] == 1 ? 'checked' : '') + " /></td>";
output += "<td style='width: 10%; text-align: center;'><input type='checkbox' " + (ar[i][3] == 1 ? 'checked' : '') + " /></td>";
output += "<td style='width: 30%;'><input type='text' value='" + ar[i][4] + "'/><input type='hidden' value='" + ar[i][5] + "' /></td>";
output += "</tr>"
}
$('#projGrid').html(output);
}
I am passing the information from vb.net using an `ArrayList.
Here is my html,
<div class="modalPopup" id="projPopup" style="width: 40%;">
<table style="width:100%;">
<tr>
<td colspan="2">
<table id="projGrid" runat="server" style="width: 100%;border: 1px solid black; font-size: 16;">
</table>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Button ID="projOk" runat="server" Text="Update" /></td>
<td>
<asp:Button ID="projCncl" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</div>
And here is my vb.net.
For Each row As HtmlTableRow In projGrid.Rows
'Dim chkBond As HtmlInputCheckBox = row.Cells(1).Controls(0)
Dim str As String
str = row.Cells(0).InnerText
Next

dynamic rows created in JS will not be available on server after postback as it is not in the viewstate
to workaround this you may do the following
you can add hidden input field to the page like
<input type="hidden" id="hiddenTableData" name="hiddenTableData" value="" />
then in your script add the data you need to the hidden input field,
$('#hiddenTableData').val(JSON.stringify(ar));
then on server on page post back, get the value of the form hidden field
String tableData= Request.Form["hiddenTableData"];
parse the hidden field value, populate your table and process it

if you are using JavaScript Method or service to fill any controls then you will not get data at code page. but you can pass that array to code page and then can get easily data as you want .
For this you should create a class same as array(in web page you are using) and a web-method
which accepts this(array) class type.

I have tried the same example in my end, and faced the same issue that , generated TR are not accessible in code behind. This is because, they are added using dynamic JS, and those are not put into VIEWSTATE, as you now, ASP control value are available in code behind on POSTBACK only if those are in VIEWSTATE. In this case it was not, so does the debugger says that projGrid.Rows.Count = 0. To make it work, you need to put changed/dynamic JS added TR into VIEWSTATE, but again those are encoded format, i afraid, how to do that.
But if you put any static TR inside table, then definitely those are accessible, I have verified that in debugger, it says projectGrid.Rows.Count = 1, if there is only one static TR inside table. And again because, that static TR is in VIEWSTATE only.
So to conclude, in my opinion, it is better to handle in JS side, if you are going to save those value to DB , then make AJAX call and save, and pass data in JSON format. Or use a hidden field, and save those data in JSON format, and after post, get those in code behind, read JSON format data, and operate.

Related

dynamic adding the row in the table using jquery working in IE8 or below but not in chrome or edge

I am working on an old IE application, where we are adding the row dynamically in the table
JS function for adding new row
function doAddVendor(vendorCode,vendorName){
var vendorTable = document.getElementById('vendorTable');
var idx = $('#vendorTable').children('TBODY').children().length-1;
var html = '';
html += '<tr tag="trVendor" class="TableLeftWhite" id="trVendor'+idx+'">';
html += '<td><input type="text" readOnly="true" tag="txtVendorCode" value="'+vendorCode+'" name="txtVendorCode'+idx+'" id="txtVendorCode'+idx+'" class="FormTextBoxReq" style="width:78%"/><input type="button" id="btn_port" name="btn_port" value=". . ." style="text-align :right;" onclick="openVendorHelp(\'txtVendorCode'+idx+'|txtVendorName'+idx+'\',\'retVendorChoosed\');" class="FormBtnClrHelp" /> </td>';
html += '<td><span id="txtVendorNameDesc'+idx+'">'+vendorName+'</span><input type="hidden" name="txtVendorName'+idx+'" id="txtVendorName'+idx+'" value="'+vendorName+'"/></td>';
html += '<td align="center"><input type="checkbox" name="chkVendorCode'+idx+'" value="'+idx+'" tag="chkCheckVendorDelete"/></td>';
html += '</tr>';
debugger;
//Below line works well in IE but on chrome its empty the previous added row
$('#vendorTable').children('TBODY').html($('#vendorTable').children('TBODY').html()+html);
$('#vendorListSize').val($('#vendorTable').children('TBODY').children().length-1);
}
HTMl CODE
<div style="height: 300px;">
<table border="0" cellpadding="0" cellspacing="1" width="100%"
id="vendorTable">
<tr>
<td width="15%" class="TableCenterSub">Vendor Code</td>
<td width="75%" class="TableCenterSub">Vendor Name</td>
<td width="10%" class="TableCenterSub">Select</td>
</tr>
</table>
</div>
first I add new row as below and fill it with some data
now when I try to add new row in chrome, its empty the previous row as below image
When I am adding the row and put any value for first time its added properly but when I tried to add new row,it empty the previous row in chrome while in IE its still populating properly.
One solution I found that I can put the check if the request is coming from IE or chrome based on that I can add the row in different way but this type of code has reutrn multiple time for multiple screens, I am looking for fix in this code so it can work smoothly without changing a lot in the files.
Any help to fix in particular code, will be much appriciate

Using plain javascript/jquery to save user sorted table order and save it in a php variable

I am facing an issue while using Jquery and PHP in same files as to sort the table. I searched quite a while found that a solution has been presented using JQuery UI to save the sorted list and then send it to php form using ajax, however due to project constraints I can't include JQuery UI as we are already using Bootstrap. So I am limited to use vanilla javascript or jquery 1.7 . Here is a snippet of my code
echo '<tr>';
echo '<td><a class="icon-pencil icon-gray" href="unit_custom_fields.php?szAction=Edit&szUnitCustomFieldId=' . $pUnitCustomField->m_uId . '" title="Edit"></a></td>';
echo '<td>' . $pUnitCustomField->m_szFieldPlaceholder . '</td>';
echo '<td>' . $pUnitCustomField->m_szFieldDescription . '</td>';
echo '<td>' . ($pUnitCustomField->m_bShowInUnitList == 1 ? "yes" : "no") . '</td>';
echo '<td>' . ($pUnitCustomField->m_bIsPasswordField == 1 ? "yes" : "no") . '</td>';
echo '<td><a class="icon-arrow-down moveDown" href="javascript:;" onclick="sortUnitCustomFields()"></a><a class="icon-arrow-up moveUp" href="javascript:;" onclick="sortUnitCustomFields()"></a>';
echo '</tr>';
Here is how the user can sort the table with up and down arrows using Jquery
global $g_szUnitCustomFieldPriority;
$g_szUnitCustomFieldPriority .= <<< END
<script type="text/javascript">
function sortUnitCustomFields() {
$('.moveUp').live('click', function(){
var row = $(this).closest('tr');
var prev = row.prev();
if (prev.length == 1) {
row.detach();
prev.before(row);
}
});
$('.moveDown').live('click', function(){
var row = $(this).closest('tr');
var next = row.next('tr');
if (next.length == 1) {
row.detach();
next.after(row);
}
});
}
</script>
END;
In order to save changes to the form I am using POST methods when the save button is clicked like
if ($szAction == 'Save') {
$pUnitCustomField->m_szFieldPlaceholder = $_POST['szFieldPlaceholder'];
}
So How can I save the sort order in the m_szFieldPlaceholder without using Jquery UI.
If the table is inside the form tag change this line and pass the placeholder through a hidden form input like:
echo '<td>' . $pUnitCustomField->m_szFieldPlaceholder . '<input type="hidden" name="szFieldPlaceholder[]" value="'.$pUnitCustomField->m_uId.'" /></td>';
Then retrieve the data like:
if ($szAction == 'Save') {
$flip = array_flip($_POST['szFieldPlaceholder']);
$order = $flip[$pUnitCustomField->m_uId];
$pUnitCustomField->m_szFieldPlaceholder = $order;
}
jQueryUI should not be needed to save your information back to the PHP-side database.
What you need to do is to:
get an updated ordering of the table rows and store in an array or some such; then
send that order back to the PHP side via ajax. (Ajax is the "system" by which javascript communicates with php).
On the PHP side, you receive the table order and
store that order into a table. THEN
you modify your normal page build to retrieve the row order data from teh database (need to also handle if it does not exist - i.e. user has not re-ordered the rows), and
then re-order the table into that order before handing control over to the user.
jQueryUI would not be needed for that process (nor can I imagine how it could be used to do the front-end/back-end communications. That is not what jQueryUI is for.)
If you would like to use jQuery UI Sortable, you can do so with jQuery v1.7. Simply use jQuery UI 1.11.4. Here is an example:
$(function() {
$("table tbody").sortable({
items: "> tr",
handle: ".sort-handle"
});
$("table .ui-icon-pencil").on("click", function() {
var id = $(this).parents("tr").data("id");
var url = "unit_custom_fields.php?szAction=Edit&szUnitCustomFieldId=" + id;
console.log("Edit: " + url);
//window.location.href = url;
});
$("button").click(function() {
var data = $("table tbody").sortable("serialize");
console.log("Sort Data: " + data);
});
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<table>
<tr id="m_uId-1" data-id="1">
<td>
<span class="ui-icon ui-icon-pencil"></span>
</td>
<td>FieldPlaceHolder 1</td>
<td>ShowInUnitList 1</td>
<td>IsPasswordField 1</td>
<td>
<span class="ui-icon ui-icon-grip-dotted-vertical sort-handle"></span>
</td>
</tr>
<tr id="m_uId-2" data-id="2">
<td>
<span class="ui-icon ui-icon-pencil"></span>
</td>
<td>FieldPlaceHolder 2</td>
<td>ShowInUnitList 2</td>
<td>IsPasswordField 2</td>
<td>
<span class="ui-icon ui-icon-grip-dotted-vertical sort-handle"></span>
</tr>
<tr id="m_uId-3" data-id="3">
<td>
<span class="ui-icon ui-icon-pencil"></span>
</td>
<td>FieldPlaceHolder 3</td>
<td>ShowInUnitList 3</td>
<td>IsPasswordField 3</td>
<td>
<span class="ui-icon ui-icon-grip-dotted-vertical sort-handle"></span>
</tr>
</table>
<button>Save</button>
Now you can make use of Sortable and it's methods, like "serialize" and "toArray" as you desire.
Hope that helps.

Trying to bind column dynamically in a table using jquery

I am trying to bind column dynamically in a table using jQuery .but click event is not working while trying to click 'btnASizeR' and 'btnWdDelete' button event is not working .Any idea would be appreciated.
$(function() {
var i = 0;
$('#btnASizeR').click(function() {
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var i = $("#WireDimTbl tbody>tr").length + 1;
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var sizerangeMin = "<input type='text' ID='SizeMin" + i + "' name='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax" + i + "' name='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin" + i + "' name='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax" + i + "' name='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Wire Dimensions</strong></td>
</tr>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type="button" id="btnASizeR" value="AddSizeRange" />
<input type="button" id="btnWdDelete" value="Delete" />
<table id="WireDimTbl" class="table table-bordered">
<thead>
<tr>
<th class="text-center">Size Range Min (mm)</th>
<th class="text-center">Size Range Max (mm)</th>
<th class="text-center">Tolerance (-)mm</th>
<th class="text-center">Tolerance (+) mm</th>
</tr>
</thead>
<tbody></tbody>
</table>
</td>
</tr>
You mentioned that you are loading the table dynamically. Do you mean that when the page first loads the table is missing and its added later?
If that is the case, are you sure the code is called that binds the click events? The above example binds the events on page_load however, if the buttons are not yet available on the page it won't be able to bind it. JQuery will not automatically bind future elements.
Try settings a console.log($('#btnASizeR')); before binding the click event to make sure that JQuery can actually find the button.

Delete a table row on button click in Javascript

I have a table with the following 3 columns where each row is dynamically appended.
Condition : Is a mere WHERE clause conditional statement string
Remove : A button that removes that row (Removes a condition)
Join with : A drop down combo
When the user clicks on the Remove button, that particular row needs to be removed.
I have written the code for this, but nothing happens and am not getting any errors on the console as well.
Code in Context
$("#whereConditionTable").append(
"<tr>"+
"<td>"+conditionString+"</td>"+
"<td><button id='removeConditionBtn' name='removeConditionBtn' class='btn btn-default'><img src='resources/images/removeWhereCondition.png' width='25px' height='25px'></button>"+
"<td>"+
"<select id='where-Condition-Join-Combo' name='where-Condition-Join-Combo' class='form-control'>"+
"<option value='1'>Join using</option>"+
"<option value='2'>AND</option>"+
"<option value='3'>OR</option>"+
"</select>"+
"</td>"+
"</tr>"
);
document.getElementById("removeConditionBtn").addEventListener("click", function() {
removeWhereCondition();
}, false);
removeWhereCondition()
function removeWhereCondition()
{
$(this).closest("tr").remove();
}
Any suggestions in this regard will be highly appreciated.
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Row 1</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
</table>
</body>
</html>
Few things to fix:
You're combining jQuery and vanilla JavaScript (getElementById), so I've tidied some of that up and rewritten it as jQuery.
HTML documents can not have repeating IDs. If your append ran more than once, it would create additional #removeConditionBtn and #where-Condition-Join-Combo elements, and JS would cease to work. I've changed these to classes, which are reusable.
Your addEventListener to bind a click event was only going to bind to (one) #removeConditionBtn element that existed when the code was first run. If the table contents changed to include additional buttons, your binding wouldn't have updated (even if you were using class rather than ID). I've rewritten this using jQuery on on the table itself, so the click event will still fire even as the contents of the table change.
Working demonstration below:
var conditionString = "text";
$("#whereConditionTable").append(
"<tr>" +
"<td>" + conditionString + "</td>" +
"<td><button class='removeConditionBtn' name='removeConditionBtn' class='btn btn-default'><img src='resources/images/removeWhereCondition.png' alt='Remove' width='25px' height='25px'></button>" +
"<td>" +
"<select class='where-Condition-Join-Combo' name='where-Condition-Join-Combo' class='form-control'>" +
"<option value='1'>Join using</option>" +
"<option value='2'>AND</option>" +
"<option value='3'>OR</option>" +
"</select>" +
"</td>" +
"</tr>"
);
$("#whereConditionTable").on("click", ".removeConditionBtn", function() {
$(this).closest("tr").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="whereConditionTable"></table>
Apparently you are using jQuery. You could try:
$('#removeConditionButton').on('click', function(element) {
$(element).closest('tr').remove();
})
By the way, it seem you are using id-property incorrectly. Id's should be unique and each page can have only one element with same id. In this case, you should use class instead of id.

Ajax with multiple form inputs

I am working on a new system and am stuck at a point with jquery + ajax and getting it work work correctly with the other things happening on the page.
Basically the page is to submit a quote and on the page you can add as many quote items as you want. When someone clicks on new item it runs the below code wich gets the value of a hidden element and uses it in all of the new elements Ids in order to keep them all unique.
New Product code:
function addFormField() {
var id = document.getElementById("field_id").value;
$("#products").append("
<table width='600' cellpadding='5' cellspacing='0' class='Add_Products' id='row" + id + "'>
<td width='250' class='left'>
<label>Select Product Category</label>
</td>
<td class='right' >
<label><select name='ProductCategory' id='ProductCategory'>
<?php foreach($categories as $key=>$category){
echo "<option value=".$key.">".$category."</option>";
}
?>
</select>
</label>
</td>
</tr>
<tr>
<td width='250' class='left'>
<label>Select Product Template</label>
</td>
<td class='right' >
<label>
<select name='data[QuoteItem][" + id + "][product_id]' id='QuoteItem" + id + "product_id'></select>
</label>
</td>
</tr>
<tr >
<td class='left'>Name</td>
<td class='right'>
<label>
<input name='data[QuoteItem][" + id + "][name]' type='text' id='QuoteItem" + id + "name' size='50' />
</label>
</td>
</tr>
<tr >
<td class='left'>
Price (ex GST)
</td>
<td class='right'>
<input type='text' name='data[QuoteItem][" + id + "][price]' id='QuoteItem" + id + "price' onchange='totalProductPrice();' class='quote-item-price' />
</td>
</tr>
<tr>
<td class='left'>
Description
</td>
<td class='right'>
<label>
<textarea name='data[QuoteItem][" + id + "][description]' cols='38' rows='5' id='QuoteItem" + id + "description'>
</textarea>
</label>
</td>
</tr>
<tr>
<td>
<a href='#' onClick='removeFormField(\"#row" + id + "\"); return false;'>Remove</a>
</td>
</tr>
</table>
");
$('#row' + id).highlightFade({
speed:1000
});
id = (id - 1) + 2;
document.getElementById("field_id").value = id;
}
The next thing i want to do is setup an AJAX query using jQuery that when selected will request the appropriate data and populate the products box but i cannot figure out how to get the ID of that set of elements to ensure that the correct dropdown box is populated and also to make sure that the onchange is detected for the correct box.
Ive tried methods like adding the ID to the id of the dropdown box but then the onchagne doesnt work.
My jquery ajax code is below that retreives the list of products
$(function(){
$("select#ProductCategory").change(function(){
var url = "productList/" + $(this).val() + "";
var id = $("select#ProductCategory").attr('name');
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
options += '<option value="0">None</option>';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteItem" + id + "product_id").html(options);
})
})
})
For the life on my cannot figure this out so if anyone could shed some light on the best way to do it that would be great.
ALso if i need to clarify further let me know because im strugling to explain it.
Thanks in advance
I have similar functionality in my project. Here how I do it:
I have a global variable that start with 0, and increased every time new field added:
var num = 0;
jQuery(function($){
$("#add_field").click(function(){
num++;
//here add new field, with id contains 'num'
});
});
to make it easier to debug, you should start with a simple element, test it so it's bug free, and add more field to it.
To submit form via AJAX, use jQuery form plugins, so you don't need to add all fields manually in ajax code that submit the form.

Categories

Resources