Trying to bind column dynamically in a table using jquery - javascript

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.

Related

using dynamic table to fill data only and pass the values to code behind ASP.NET

It's been a long time since I coded so I am facing troubles.
I am using VS2015 .NET c# webForms Application. I have a simple form where the user need to fill a dynamic table and after hitting submit the values are passed to code behind for some calculation then stored in DB.
I used the HTML table in the link http://talkerscode.com/webtricks/add-edit-and-delete-rows-from-table-dynamically-using-javascript.php
the output:
I cant use Gridview becuase it postsback and connects to DB directly. I dont want to store the input of the table immediately.
I am stuck at retrieving the data from HTML table.
Can I get some hints or suggest to me any other better way to do if any.
If you want I can provide the code.
Thanks
UPDATE:
my code
form.aspx
<form runat="server">
//elements here
<div class="table-responsive" id="div_invlv">
<!------TABLE ---->
<table id="data_table" class="table" >
<tr>
<th></th>
<th> </th>
<th>Name</th>
<th>Position</th>
<th>Company</th>
<th></th>
</tr>
<tr>
<td>
<select class="form-control" id="type_of_person">
<option>Internal</option>
<option>External</option>
</select> </td>
<td><input type="text" class="form-control" id="new_name" /></td>
<td><input type="text" class="form-control" id="new_position" /></td>
<td><input type="text" class="form-control" id="new_company" /></td>
<td><input type="button" class="btn btn-small btn-template-main add" onclick="add_row();" value="Add Row" /></td>
</tr>
</table>
</form>
Table.js
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row()
{
var drop = document.getElementById("type_of_person");
var new_type = drop.options[drop.selectedIndex].innerHTML;
var new_name=document.getElementById("new_name").value;
var new_country=document.getElementById("new_position").value;
var new_company=document.getElementById("new_company").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='id_row" + table_len + "'><asp:Label Name='id" + table_len + "' runat='server' > " + table_len + "</asp:Label></td> <td id='Type_row" + table_len + "'><asp:Label ID='type" + table_len + "' runat='server' > " + new_type + "</asp:Label></td><td id='name_row" + table_len + "'> <asp:Label ID='name'"+table_len+" runat='server' >" + new_name + "</asp:Label></td><td id='position_row" + table_len + "'>" + new_country + "</asp:Label></td><td id='company_row" + table_len + "'><asp:Label ID='company'"+table_len+" runat='server' >" + new_company + "</asp:Label></td><td > <input type='button' value='Delete' class='btn btn-small btn-template-main delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_position").value = "";
document.getElementById("new_company").value = "";
}
C#
string typeTable = Request.Form["type" + 1];
Label10.Text = typeTable ;
The rows are generated during the run and I am trying to retrieve the value of one cell in the first row for testing but its not working.
The link provided by #legends
https://www.aspsnippets.com/Articles/Dynamically-Add-Rows-to-GridView-using-JavaScript-on-Button-Click-in-ASPNet.aspx
works great and solved most of my issue.
Thanks
you can use this function to fill your datagrid dyamically
public void fillgrid(string qry, GridView dg){
try
{
sql.cmd = new SqlCommand("qry", sql.cn);
sql.cn.Open();
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sql.cmd);
sda.Fill(ds);
dg.DataSource = ds;
dg.DataBind();
sql.cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
or you can use a placeholder control to create a dyamic html table

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.

Variables created in Jquery not appearing in Debugger

I have written some code in Jquery that when a button is pressed, creates a new variable and displays it on the screen. I'd like to take whatever data is entered into this new variable and store it in a database however before I get there I have to figure out to access the variables information properly.
In HTML I have 3 text boxes created and a button to add up to 7 more for a total of 10. My code looks like this (and these store in the database just fine):
<table style="width:90%" class="Long-Term-Conditions">
<center>
<tr>
<td><b><center>Long term condition 1:</center></b></td>
<td><center><input type='text' id="Var1" name ='Var1' value='%Var1%' /></center></td>
</tr>
<tr>
<td><b><center>Long term condition 2:</center></b></td>
<td><center><input type='text' id="Var2" name ='Var2' value='%Var2%' /></center></td>
</tr>
<tr>
<td><b><center>Long term condition 3:</center></b></td>
<td><center><input type='text' id="Var3" name ='Var3' value='%Var3%' /></center></td>
</tr>
</center>
</table>
Add another long-term health condition
<div id="Message"></div>
My problem now is that my Jquery variables cant be inspected (says not available) and no data is passed to the database after. My Jquery looks like this:
<script>
//Adds another row to the above table.
var counter = 3;
jQuery('a.add-cond').click(function(event){
event.preventDefault();
if (counter < 10) {
counter++;
var newRow = jQuery('<tr><td><b><center>'+ "Long term condition "+ counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
counter + '" id="Var' + counter + 'value="%Var' + counter + '%"/></center></b></td></tr>');
jQuery('table.Long-Term-Conditions').append(newRow);
}
else
{
document.getElementById("add-cond").style.visibility = "hidden";
document.getElementById("Message").innerHTML = '<font color="Red">Please
contact us</font>';
}
});
</script>
The code works in creating the new variable however any data entered into the newly created text box is never passed to the debugger or the database. What am I doing wrong? Any help is appreciated.
The problem you are having is that when you bind the click event to the elements it only binds to the elements that already exist on the document. So when you add new ones it won't trigger that click event because you didn't bind it to the new ones.
A simple solution to this is to add the click event listener to the body like so:
jQuery('body').on('click', 'a.add-cond', function(event){
I think that is what you are looking for.
Also like the other guy mentioned you are missing a closing quote and a space
id="Var' + counter + 'value="%Var' + counter + '%"
Should be:
id="Var' + counter + '" value="%Var' + counter + '%"
I think you were just missing a " between the id and value of your new input
//Adds another row to the above table.
var counter = 3;
jQuery('a.add-cond').click(function(event) {
event.preventDefault();
if (counter < 10) {
counter++;
var newRow = jQuery('<tr><td><b><center>' + "Long term condition " + counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
counter + '" id="Var' + counter + '" value="%Var' + counter + '%"/></center></b></td></tr>');
jQuery('table.Long-Term-Conditions').append(newRow);
} else {
document.getElementById("add-cond").style.visibility = "hidden";
document.getElementById("Message").innerHTML = '<font color="Red">Please contact us </font>';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:90%" class="Long-Term-Conditions">
<center>
<tr>
<td><b><center>Long term condition 1:</center></b></td>
<td>
<center><input type='text' id="Var1" name='Var1' value='%Var1%' /></center>
</td>
</tr>
<tr>
<td><b><center>Long term condition 2:</center></b></td>
<td>
<center><input type='text' id="Var2" name='Var2' value='%Var2%' /></center>
</td>
</tr>
<tr>
<td><b><center>Long term condition 3:</center></b></td>
<td>
<center><input type='text' id="Var3" name='Var3' value='%Var3%' /></center>
</td>
</tr>
</center>
</table>
Add another long-term health condition
<div id="Message"></div>

Append HTML input with value="' + variable + '" is not giving me the correct value

I got a table (which gets created with PHP (data from mySQL)) that look like this:
<table class="data-table">
<tbody>
<tr>
<td class="databasecontent">maybe some values</td>
<td class="databasecontent">maybe empty</td>
</tr>
<tr>
<td class="databasecontent">another row</td>
<td class="databasecontent"></td>
</tr>
</tbody>
</table>
Then I got a list, which I want the content to append to:
<ul class="plannerlist" id="plannerlist2">
</ul>
(I got 6 <ul> in total with id="plannerlist1, 2, ...").
So I want the text from .databasecontent:nth-child(1) to append to ul#plannerlist1 with this JS:
var database1 = $("td.databasecontent:nth-child(1)").text;
$("ul#plannerlist1:visible").append('<input type="text" readonly value="' + database1 + '">');
var database2 = $("td.databasecontent:nth-child(2)").text;
$("ul#plannerlist2:visible").append('<input type="text" readonly value="' + database2 + '">');
and so on...
I think that jQuery should work but it's just giving me an input with the value:
function (a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)}
Whats the problem with my code?
You should use .text() instead of using .text and it will work perfectly if nothing wrong you have done.
By using var database2 = $("td.databasecontent:nth-child(2)").text; you return function text itself, not the result of it. Try var database2 = $("td.databasecontent:nth-child(2)").text();.

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