jQuery to add and remove textboxes - just removes everything or nothing - c#

So I have a simple ASP.NET/ C# generated html form where I have a list of textboxes that I want to be able to add and/or delete on the fly. There are pre-existing textboxes that are generated from a SP that look like this, with an 'add another textbox' button below:
<tr>
<td id="lblRole" style="vertical-align:top;" ><strong>The Role *</strong><br />(2000 characters maximum each)</td>
<td id="rolesColumn">
<div id="roles-1" class="div_row">
<textarea name="ctl00$mainContent$uxRolesList$ctl01" rows="5" cols="100"
id="ctl00_mainContent_uxRolesList_ctl01">yuyuy</textarea>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" /><br /><br />
</div>
<input type="hidden" name="ctl00$mainContent$uxTxtBoxRolesCount"
id="ctl00_mainContent_uxTxtBoxRolesCount" value="1" />
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="ctl00$mainContent$uxAddRoleBtn"
value="Add a new role requirement"
id="ctl00_mainContent_uxAddRoleBtn" class="btn" />
</td>
</tr>
My jQuery is this:
$("#ctl00_mainContent_uxAddRoleBtn").live("click", (function (e) {
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
rolesCounter++;
if (rolesCounter < 10) {
var rolesCounterText = "0" + rolesCounter;
} else {
var rolesCounterText = rolesCounter;
}
$('#rolesColumn').append("<div id='roles-" + rolesCounter + "' class='div_row'><textarea name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "' rows='5' cols='100' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "'></textarea><input class='remove-roles-btn' type='button' value='X' style='vertical-align:top;' /><br /><br /></div>");
e.preventDefault();
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
}));
$(".remove-roles-btn").on("click", (function (e) {
$(this).parents('.div_row').remove();
e.preventDefault();
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
rolesCounter--;
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
}));
But when I click to add a new textbox, all the textboxes are deleted.
And when I click to delete a textbox, nothing happens.
Thank you.

You have a typo in your code:
$("#ctl00_mainContent_uxAddRoleBtn").live("click", (function (e) {
//-------------------------------------------^----here you can see a "("
and here:
$(".remove-roles-btn").on("click", (function (e) {
//------------------^-----------------here
but i suggest you to use .on() method:
$(document).on("click", "#ctl00_mainContent_uxAddRoleBtn", function (e) {
and this:
$(document).on("click", ".remove-roles-btn", function (e) {

NOTE, be sure to be using jQuery 1.8.3 or lower, otherwise it will NOT work. All you have to do is change 'on' to 'live'
$(".remove-roles-btn").live("click", (function (e) {
Here is a simple example with your code that shows it working.

For remove button you need to use event delegation
$(document).on("click", "#rolesColumn .remove-roles-btn", function (e) {
e.preventDefault();
$(this).closest('.div_row').remove();
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter - 1);
});
$(document).on("click", "#ctl00_mainContent_uxAddRoleBtn", function (e) {
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
rolesCounter++;
if (rolesCounter < 10) {
var rolesCounterText = "0" + rolesCounter;
} else {
var rolesCounterText = rolesCounter;
}
$('#rolesColumn').append("<div id='roles-" + rolesCounter + "' class='div_row'><textarea name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "' rows='5' cols='100' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "'></textarea><input class='remove-roles-btn' type='button' value='X' style='vertical-align:top;' /><br /><br /></div>");
e.preventDefault();
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
});
Demo: Fiddle

Related

Passing Values from React form to Controller and displaying result

I have a question about using react with a function I set up in C# that has a controller to get values via the URL.
This is the Controller:
[HttpGet("{number}/{source}/{aux}/{destination}")]
public string Get(int number, string source, string aux, string destination)
{
Hanoi h = new Hanoi();
return h.MoveDisks(number, source, aux, destination);
}
This is what I've tried so far:
<script type="text/babel">
var Form = React.createClass({
calculate: function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("moves").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "api/values" + "/" + "number" + "/" + "src" + "/" + "aux" + "/" + "dest", true);
xhttp.send();
},
render: function (){
return (
<div>
Number of rings: <input type="number" id="number"/> <br /><br />
Source: <input type="text" id="src"/><br /><br />
Auxiliary: <input type="text" id="aux"/><br /><br />
Destination: <input type="text" id="dest"/><br /><br />
<button onClick={this.calculate}>Get Result!</button>
</div>
);
}
});
ReactDOM.render(<Form />, document.getElementById('form'));
</script>
<div id="form"></div>
<div id="moves"></div>
I want the result to be posted in the "moves" div, but can't figure out how. Am I trying to use React in a way it's not supposed to work?
I'm a beginner so any help is appreciated.
You need to correct api route
[HttpGet]
[Route("api/values/{number}/{source}/{aux}/{destination}")]
public string Get(int number, string source, string aux, string destination)
{
Hanoi h = new Hanoi();
return h.MoveDisks(number, source, aux, destination);
}

I am adding and deleting the row dynamically using jQuery, now i want the values entered into that to store into DB using ASP.NET

Below is the code of jQuery which helps me to add and delete the row dynamically, but now i want to add the data entered into these dynamic rows into DB and specifically using ASP.NET.I am not getting any idea and very much new to ASP.NET. And there 2 fields which accepts the date. Help me out please!.
$(document).ready(function () {
var lastChar = 1, newRow;
get_lastID = function () {
var id = $('#experience_table tr:last-child td:first-child input').attr("name");
lastChar = parseInt(id.substr(id.length - 2), 10);
lastChar = lastChar + 1;
newRow = "<tr> \
<td><input type='text' name='company_name_0" + lastChar + "' maxlength='255' /></td> \
<td><input type='text' class='datePicker' name='from_0" + lastChar + "' /></td> \
<td><input type='text' class='datePicker' name='to_0" + lastChar + "' /></td> \
<td><input type='number' name='Total_exp_0" + lastChar + "' maxlength='11' /></td> \
<td><input type='button' value='Delete' class = 'del_ExperienceRow' /></td> \
</tr>"
}
$("#add_ExperienceRow").on("click", function () {
if ($('#experience_table tr').size() <= 9) {
get_lastID();
$('#experience_table tbody').append(newRow);
} else {
alert("Reached Maximum Rows!");
};
$('.datePicker').datepicker();
});
$('.datePicker').datepicker();
$(document).on('click', '.del_ExperienceRow', function () {
$(this).closest('tr').remove();
lastChar = lastChar - 2;
});
});
});
You have to create a save button that will store all your rows and the entered data in an array and send the data to the server like this:
function saveRows() {
var data = []; // Creates an array
// Create a foreach loop over all rows
$("#experience_table tr").each(function() {
var row = $(this);
// This adds an element to the array for the current row, containing an
// anonymous object with the data of the current row
data.push({ someData: $(row).find("td.experience").val() });
});
$.ajax( { ... } ) // Create ajax call to your server (webservice)
}
Then you will need a webservice on the serverside. This is the ASP.NET part.
I would suggest you to setup a WCF service. Take a look at a tutorial here:
http://www.codeproject.com/Articles/627082/How-to-Consume-WCF-Service-using-JavaScript-Proxy
If you have further questions feel free to ask!
Here is an example of how I send an email with ASP and jQuery. The principles are the same so You will be able to adapt it well.
jQuery
function sendEmail() {
$("#email").dialog({
modal: true,
width: 550,
buttons: {
"Send": function () {
var btn = document.getElementById("<%=lbSend.ClientID %>");
if (btn) btn.click();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
jQuery("#email").parent().appendTo(jQuery("form:first"));//this is key as it makes sure it finds the textboxes within the dialog. Without this, you will insert blank values.
}
ASP
<div class="popUpStyle" title="Send Email" id="email" style="display: none">
<asp:Label ID="lblTo" runat="server" Text="To: " Font-Bold="true"></asp:Label><asp:Label runat="server" ID="lblSendTo" Text=""></asp:Label> <asp:Label ID="lblFrom" Font-Bold="true" runat="server" Text="From: "></asp:Label><asp:Label runat="server" ID="lblSendFrom" Text="Training.Registration#JeffWyler.com"></asp:Label>
<br />
<asp:Label ID="lblSubject" Font-Bold="true" runat="server" Text="Subject: "></asp:Label><asp:TextBox ID="tbSubject" runat="server" Width="200px"></asp:TextBox>
<br />
<asp:Label ID="lblBody" Font-Bold="true" runat="server" Text="Message:"></asp:Label>
<br />
<asp:TextBox ID="tbMessage" runat="server" Width="515px" TextMode="MultiLine" Height="150px"></asp:TextBox>
<asp:LinkButton ID="lbSend" runat="server" Text="" Width="50px" Font-Size="smaller" OnClick="lbSend_Click"></asp:LinkButton>
</div>
Code Behind C#
protected void lbSend_Click(object sender, EventArgs e)
{
//code to your database
}
So with yours, you will have to change it around a bit. You will have to create a function that calls a hidden "div." As you can tell, in the ASP markup, I am using asp controls, so I can call them from the behind code. I also use a link button with no text (if you set visible to false, you are unable to fire the button). In my jQuery, I created my own "Send" button and search for the link button within the div and once that "Send" button is clicked, the link button event is fired. Like I said before, this is sending an email so your button click event will be different. If you need help writing to the DB, let me know!
Hope this helps!

Calling jquery in default.aspx

I am new to asp.net, I am trying to add a field "Experience", when user adds company name, from date and to date. for that I am using a , now for that I am using jQuery. to add new columns dynamically i have written the jQuery function, but i am not getting where to add those function, when i run only single column is coming.Please help out how to add jQuery code into ASP.NET below is my function
var $lastChar =1, $newRow;
$get_lastID = function(){
var $id = $('#experience_table tr:last-child td:first-child input').attr("name");
$lastChar = parseInt($id.substr($id.length - 2), 10);
$lastChar = $lastChar + 1;
$newRow = "<tr> \
<td><input type='text' name='company_name_0"+$lastChar+"' maxlength='255' /></td> \
<td><input type='text' name='from_0"+$lastChar+"' /></td> \
<td><input type='text' name='to_0"+$lastChar+"' /></td> \
<td><input type='number' name='Total_exp_0"+$lastChar+"' maxlength='11' /></td> \
<td><input type='text' name='edit_0"+$lastChar+"' maxlength='255' /></td> \
<td><input type='button' value='Delete' class='del_ExperienceRow' /></td> \
</tr>"
return $newRow;
}
}
$('#add_ExperienceRow').live("click", function(){
if($('#experience_table tr').size() <= 9){
$get_lastID();
$('#experience_table tbody').append($newRow);
} else {
alert("Reached Maximum Rows!");
};
});
$(".del_ExperienceRow").live("click", function(){
$(this).closest('tr').remove();
$lastChar = $lastChar-2;
});
Wrap your code into this function and script tag
<script src="Script/jquery-version.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//Your code goes here
});
</script>
You should also change that .live event handler to .on if you are using recent jQuery version.

"inserting the dynamically generated rows into the table"

I am bit new in the c# programming, so I got stuck at one place. Need your help.
Actually through javascript I am generating table(4 columns) rows(having textboxes so that user can give inputs) as per as the user button click. As the number of rows are not fixed and we dont have the exact name of the textboxes so now my problem is how should we insert these rows into the sqlserver table?
should I use simply the loop for generating the name of the Textboxes for every user button click? and once we got the name for all controls can we insert these all through a single insert statement by using loop?
warm regrads,
ammy
If you're using just a regular html table add 'runat="server"' Tag with JS as well as html form controls then just change TableRow to HtmlTableRow and TextBox to HtmlInputText. All of those controls are in the System.Web.UI.HtmlControls namespace.
Assuming you're using the Table server control then it's just:
foreach (TableRow row in table.Rows)
{
var col2 = (TextBox)row.Cells[1].Controls[0];
//Do DB inserting stuff here With col2
string stringToInsert= col2 .Text;
}
I'm asuming you're using MVC..
You can start by creating a model such as:
public class YourModel
{
public IEnumerable<Users> users { get; set; }
}
Than create a view and add the rows dynamically by script given below:
<script type="text/javascript">
var Rows = 1;
// We already got the 0 element as html so start from 1
function AddUser() {
$("#UserTable").append('<tr>' +
'<td><input type="text" name="users[' + Rows + '].Name" style="width:100px;" /></td>' +
'<td><input type="text" name="users[' + Rows + '].Surname" style="width:100px;" /></td>' +
'<td><input type="text" name="users[' + Rows + '].Age" style="width:50px;" /></td>' +
'<td><input type="text" name="users[' + Rows + '].Date" style="width:70px;" /></td>' +
'</tr>');
// Add datepicker (this is an optional jQueryUI stuff)
$('input[name="users[' + Rows + '].Date"]').datepicker({ dateFormat: 'yy.mm.dd' });
// Go to next row
Rows = Rows + 1;
}
$(document).ready(function(){
// Create an empty row on load
AddUser();
// Than on each click add another row
$('input[type=button]').click(function(){ AddUser(); });
});
</script>
<div>
<table id="UserTable">
<tr>
<td><input type="text" name="user[0].Name" style="width:100px;" value="Berker" /></td>
<td><input type="text" name="user[0].Surname" style="width:100px;" value="Yüceer" /></td>
<td><input type="text" name="user[0].Age" style="width:50px;" value="24" /></td>
<td><input type="text" name="user[0].Date" style="width:70px;" value="2012.12.11" /></td>
</tr>
</table>
<input type="button" id="add" value="Add" />
</div>
fiddle for the script: http://jsfiddle.net/BerkerYuceer/YFecD/
From your controller you can get the values as show below:
// Thanks to LinqToSql you can define ur Sql-DB this way
YourDBDataContext db = new YourDBDataContext();
//
// POST: /YourForm/Edit
[HttpPost]
public ActionResult Edit(YourModel model)
{
try
{
// if users not empty..
if (model.users != null)
{
// Each User in Users
foreach (var user in model.users)
{ // Save it to your Sql-DB
db.Users.InsertOnSubmit(user);
db.SubmitChanges();
}
}
// Return
return RedirectToAction("Index");
}
catch (Exception ex)
{
return RedirectToAction("Error", new { ErrorMessage = "Message[" + ex.Message + "] - Source[" + ex.Source + "] - StackTrace[" + ex.StackTrace + "] - Data[" + ex.Data + "]" });
}
}
//
// GET: /YourForm/Error
public ActionResult Error(String ErrorMessage)
{
ViewData["Error"] = ErrorMessage;
return View();
}
simple as this!

JQuery Dialog on table row

I am using c# and razor to produce a list of invoices. Each invoice is a table row and has a huge list of notes against it. To avoid a massive amount of space between rows, I want to hide the notes and allow a pop to view it. It is currently:
<td>
#foreach (var invoiceLine in invoice.InvoiceLines)
{
<p>
<strong>#invoiceLine.Date.ToShortDateString() #invoiceLine.Username</strong> <br />
#Html.Raw(invoiceLine.Notes.Replace(Environment.NewLine, "<br />"))
#Html.Raw((invoiceLine.DueDate.HasValue ? "<br /><strong>Follow up:</strong> " + invoiceLine.DueDate.Value.ToShortDateString() : ""))
#Html.Raw(invoiceLine.Completed ? "<br /><strong>Completed</strong>" : "")
</p>
}
So what I want to do is to add the popup using jquery:
$(function () {
$('#clickMe').click(function (event) {
var mytext = $('#myText').val();
$('<div id="dialog">' + mytext + '</div>').appendTo('body');
event.preventDefault();
$("#dialog").dialog({
width: 600,
modal: true,
close: function (event, ui) {
$("#dialog").hide();
}
});
}); //close click
});
Then modify my code:
<td>
<h3 id="clickMe">Open Notes</h3>
<textarea cols="1" rows="75" id="myText" style="display:none">
#foreach (var invoiceLine in invoice.InvoiceLines)
{
<p>
<strong>#invoiceLine.Date.ToShortDateString() #invoiceLine.Username</strong> <br />
#Html.Raw(invoiceLine.Notes.Replace(Environment.NewLine, "<br />"))
#Html.Raw((invoiceLine.DueDate.HasValue ? "<br /><strong>Follow up:</strong> " + invoiceLine.DueDate.Value.ToShortDateString() : ""))
#Html.Raw(invoiceLine.Completed ? "<br /><strong>Completed</strong>" : "")
</p>
}
</textarea>
</td>
First problem is, that only the first row appears. I presume because my id is the same all the way down?
How do I make the dialog open for each row?
I am a newb at c# and js btw :)
First: The textarea makes no sense at all.
Then change the parts like this. See it working in the jsfiddle.
HTML
<td>
#foreach (var invoiceLine in invoice.InvoiceLines)
{
<p>
<strong>#invoiceLine.Date.ToShortDateString() #invoiceLine.Username</strong> <br />
#Html.Raw((invoiceLine.DueDate.HasValue ? "<br /><strong>Follow up:</strong> " + invoiceLine.DueDate.Value.ToShortDateString() : ""))
#Html.Raw(invoiceLine.Completed ? "<br /><strong>Completed</strong>" : "")
<h3 class="notesClick">Open Notes</h3>
<div class="notesHtml" style="display:none">
#Html.Raw(invoiceLine.Notes.Replace(Environment.NewLine, "<br />"))
</div>
</p>
}
</td>
JS
$(function() {
$('.notesClick').click(function(event) {
var notes = $(event.currentTarget).next('.notesHtml');
$("<div>").html(notes.html()).dialog();
});
});​

Categories