Embedding Custom TableElement in another Custom element - dart

I would like to embed phone-component.html in another phone-view-component.html custom element. In the columns of the phone-view-component.html there is a 'Type', 'Provider', 'Number' - all text - and a button - 'New' - in the final column. I would like use the 'New' button in the phone-view-component to add a phone-component consisting of a <select>, <datalist> and <tel> and <button> ('Delete') under each of the the first row. So each time I clicked the 'New' button a new row would be inserted. The 'Delete' button would remove the row of which it is a part.
My attempts so far are shown below:
phone-component.html
<!DOCTYPE html>
<polymer-element name='epimss-phone-component'>
<template>
<roole src="reg-roole.rin" monitor="1"></roole>
<table border="1" width="100%">
<tbody>
<tr>
<td>
<select id="phoneCmbo" selectedIndex='{{phoneSelectedIndex}}' >
<option value="{{phone}}"
template repeat="{{phone in phones}}" >{{phone}}
</option>
</select>
</td>
<td>
<input id='providerTxt' type='text' value='{{phone.provider}}' list='providers'>
<datalist id='providers'>
<template repeat='{{provider in providers}}'>
<option value='{{provider}}'>{{provider}}</option>
</template>
</datalist>
</td>
<td><input id='num' type='tel' value='{{phone.num}}'>
</td>
<td>
<button id='deleteBtn on-click={{deleteRow}}'></button>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</template>
<script type="application/dart">
import 'package:polymer/polymer.dart' show CustomTag, PolymerElement, observable;
import 'dart:html' show Event, Node;
import 'package:epimss_polymer/reg_popo.dart' show Phone;
#CustomTag( 'epimss-phone-component' )
class PhoneElement extends PolymerElement
{
#observable Phone phone = new Phone();
List<String> phones = ['', 'Car', 'Fax', 'Home', 'Home Fax', 'Home Mobile',
'Home Video', 'Mobile', 'Pager', 'Work',
'Work Direct', 'Work Fax', 'Work Mobile', 'Work Video',
'Next-of-Kin Home', 'Next-of-Kin Mobile',
'Next-of-Kin Work', 'Tollfree', 'Web Phone'];
List<String> providers = [ '', 'AT&T', 'Digicel', 'Flow', 'Lime' ];
int providerSelectedIndex = 0;
//#observable Map phone = toObservable( new Phone() );
PhoneElement.created() : super.created();
void addRow( Event e, var detail, Node target)
{
print( 'New row created' );
}
void deleteRow( Event e, var detail, Node target)
{
print( 'Current row deleted' );
}
}
</script>
</polymer-element>
phone-view-component.html
<!DOCTYPE html>
<link rel="import" href="phone-component.html">
<polymer-element name='epimss-phone-view-component'>
<template>
<roole src="reg-roole.rin" monitor="1"></roole>
<table border="1" width="100%">
<tbody>
<tr>
<td><label id='typeLbl' for='typeDlst'>Type</label></td>
<td><label id='providerLbl' for='providerDlst'>Provider</label></td>
<td><label id='numberLbl' for='numberTxt'>Number</label></td>
<td><input id='newBtn' type='button' value='New' on-click='{{addRow}}'>
</tr>
</tbody>
</table>
<epimss-phone-component></epimss-phone-component>
</template>
<script type="application/dart">
import 'package:polymer/polymer.dart' show CustomTag, observable;
import 'dart:html' show Event, Node;
import 'package:roole_element/element.dart' show RooleElement;
import 'package:epimss_polymer/reg_popo.dart' show Phone;
#CustomTag( 'epimss-phone-view-component' )
class PhoneViewElement extends RooleElement
{
#observable Phone phone = new Phone();
PhoneViewElement.created() : super.created();
}
</script>
</polymer-element>
phone.dart
part of reg_popo;
class Phone extends Observable
{
String type = '';
String provider = '';
String num = '';
}
I don't know how to place widget in each of the table columns and retrieve each row of new data in a List model.
Any help is appreciated.
Thanks

Related

fetch Data into angular2 form

i am trying to fetch users data back into form but i am unable to do so,
please help me,
here is my code.
i want to get the data loaded into the edit form on OnInit(), i am using angular 4 , and backend is .Net MVC,
and also explain what's wrong in my code.
code for list component
enter code here
`<table class="table table-hover">
<thead>
<tr>
<th>Contact ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone </th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let contact of contacts">
<td>{{ contact.ContactID }}</td>
<td>{{ contact.FirstName }}</td>
<td>{{ contact.LastName }}</td>
<td>{{ contact.Phone }}</td>
<td>{{ contact.Email }}</td>
<a [routerLink]="['/contactedit', contact.ContactID]">Edit</a>
<!-- <td><a (click) = "onEdit( contact.ContactID )" class="btn btn-primary" >Edit</a> </td> -->
<td><a (click) = "onDelete( contact.ContactID)" class="btn btn-primary" >Delete</a></td>
</tr>
</tbody>
</table>`
here is the html of edit form component
`<form
[formGroup] = "form"
(ngSubmit) = "onSubmit(form.value)">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" class="form-control" id="FirstName" placeholder="Enter email" formControlName="FirstName">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="LastName" placeholder="Password" formControlName="LastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="tel" class="form-control" id="Phone" placeholder="Password" formControlName="Phone">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="Email" placeholder="Password" formControlName="Email" >
</div>
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Update</button>
<button type="reset" class="btn btn-default">Clear</button>
</form>`
here is the code of edit form component.ts
`import { Component , OnInit } from '#angular/core';
import { FormBuilder,Validators, FormGroup } from '#angular/forms';
import { Contact } from './contact.interface';
import { ActivatedRoute , Router } from '#angular/router';
import { MediaService } from './media.service';
import 'rxjs/add/operator/switchmap';
#Component({
selector: 'my-media-form',
//moduleId: module.id,
templateUrl: 'app/media-form.component.html'
})
export class MediaFormEditComponent implements OnInit {
id: string;
currentContact: Contact;
contactForm: FormGroup;
private sub: any;
form;
constructor(private router: Router,
private route : ActivatedRoute,
private formBuilder: FormBuilder,
private mediaService: MediaService){}
ngOnInit(){
debugger;
this.form = this.formBuilder.group({
FirstName: this.formBuilder.control('',Validators.required),
LastName: this.formBuilder.control('',Validators.required),
Email: this.formBuilder.control('', Validators.compose([Validators.required])),
Phone: this.formBuilder.control('',Validators.required)
});
this.sub = this.route.params
.map(params => params['id'])
.switchMap(id => this.mediaService.getContactById(id))
.subscribe((cont: Contact) => {
this.currentContact = cont;
this.contactForm.setValue({
FirstName : cont.FirstName,
LastName: cont.LastName,
Email: cont.Email,
Phone: cont.Phone
});
});
}
onSubmit(Data){
this.mediaService.UpdateContact(Data)
.subscribe(data => this.router.navigate(['contacts']));
}
}`
First create an array before your loop (after fetch data):
let newFormArray: FormGroup[] = [];
In your loop:
newFormArray.push(this.fb.group({ FirstName: [cont[i].FirstName, Validators.required], LastName: [cont[i].LastName, Validators.required] //...
}));
Then make your form:
this.form = this.fb.group({
array: this.fb.array(newFormArray)
})
Imports: import { FormControl, FormArray, FormGroup, FormBuilder, Validators } from '#angular/forms';

How to show partial view with parameter on click

I have a database with people and phones and i created a partial view that shows persons phones. I want this patial view to be loaded on click at some button like ShowPhones or something like that.
This is how i call view
#Html.Partial("ShowPersonsPhones", item.phones)
This is my partial view
#model IEnumerable<Project.Models.Phone>
<h2>Parial View</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Numer)
</th>
<th>
#Html.DisplayNameFor(model => model.Model)
</th>
</tr>
#foreach (var phone in Model)
{
<tr>
<td>
#Html.DisplayFor(item => phone.Numer)
</td>
<td>
#Html.DisplayFor(item => phone.Model)
</td>
</tr>
}
</table>
EDIT:
i tried to do some javascript in view but it just doesnt work
<style>
.shown{
display : inline;
}
.hidden{
display : none;
}
</style>
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function show_partial(i) {
alert("show partial " + i);
var divsname = '#partial' + i;
div = $(divsname);
if (div.hasClass('hidden'))
{
div.removeClass("shown");
div.addClass("hidden");
}
else
{
div.removeClass('hidden');
div.addClass("shown");
}
}
</script>
When i put alert in the function it shows but doesnt change classes for some reason.
In button click event, you can load the partial view.
ViewPage
<input type="button" id="btn" value="ClickMe" onclick="loadPartialView()" />
<div id="partialDiv"></div>
<script type="text/javascript">
function loadPartialView() {
$("#partialDiv").load('#Url.Action("IndexView","Home")');
}
</script>
In Controller, you can return the partial view with the parameter.
public ActionResult IndexView()
{
return PartialView("_PartialView", db.Phones.ToList());
}

How to open the same jQuery Dialog from dynamically and non-dynamically created controls

I need to open the same jQuery dialog from different input text controls (including those that have been created dynamically)
This is what my page displays when it loads for the first time.
When the user presses the "Add" button a new row is added to the table
So far so good. The problem comes when I have to open the dialog that will let users enter text into the inputs ( the dialog will display upon clicking on them)
At first , I thought it would only be necessary to add a class to all the controls and then using the class selector just call the dialog.
Unfortunately then I learned that with dynamic controls you have to use ".on" to attach them events.
Once overcome these difficulties , I run into one more that I haven't been able to solve yet. This is that if you don't want the dialog to be automatically open upon initialization, you have to set "autoOpen" to false. I did so but the only result I got was that none on the inputs worked.
I have also tried putting all the code ,regarding the dialog, into a function and then calling that function when an input is clicked
I did also try declaring a variable and setting that variable to the dialog , something like this:
var dialog= $( "#dialog" )
But it didn't work either
I have tried some possibles solutions , but no luck as of yet.
EDIT : Here's a fiddle so you can have a better idea of what I'm talking about:
http://jsfiddle.net/3BXJp/
Full screen result: http://jsfiddle.net/3BXJp/embedded/result/
Here is the html code for the aspx page (Default.aspx):
<form id="form1" runat="server">
<div>
<fieldset>
<legend>Expression Builder</legend>
<table id="myTable" class="order-list">
<thead>
<tr>
<td colspan="2">
</td>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">
IF(<input type="text" name="condition1" class="showDialog" />
:
</td>
<td>
<input type="text" name="trueValue" class="showDialog" />
)
</td>
<td>
<a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" id="addrow" value="+ Add" />
</td>
</tr>
<tr>
<td colspan="">
ELSE (
<input type="text" name="else" id="else" class="showDialog" />)
</td>
</tr>
</tfoot>
</table>
</fieldset>
<br />
<input type="button" id="btnEnviar" value="Send" />
</div>
<div id="dialog-form" title="Add New Detail">
<p>
All the fields are required.</p>
<table>
<tr>
<td>
<label for="condition" id="lblcondition">
Condition</label>
</td>
<td>
<input type="text" name="condition" id="condition" class="text ui-widget-content ui-corner-all" />
</td>
</tr>
<tr>
<td>
<label for="returnValue" id="lblreturnValue">
Return Value</label>
</td>
<td>
<input type="text" name="returnValue" id="returnValue" class="text ui-widget-content ui-corner-all" />
</td>
</tr>
</table>
</div>
</form>
and here is the javascript code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$("button, input:submit, input:button").button();
$('input:text').addClass("ui-widget ui-state-default ui-corner-all");
var NewDialog = $("#dialog-form");
NewDialog.dialog({ autoOpen: false });
var Ventana = $("#dialog-form");
$("#addrow").on("click", function () {
var counter = $('#myTable tr').length - 2;
$("#ibtnDel").on("click", function () {
counter = -1
});
var newRow = $("<tr>");
var cols = "";
cols += '<td>ELSE IF(<input type="text" name="condition' + counter + '" class="showDialog1" /> </td>';
cols += '<td>: <input type="text" name="TrueValue' + counter + '" class="showDialog1" />)</td>';
cols += '<td><input type="button" id="ibtnDel" value="-Remove"></td>';
newRow.append(cols);
var txtCondi = newRow.find('input[name^="condition"]');
var txtVarlorV = newRow.find('input[name^="TrueValue"]');
newRow.find('input[class ="showDialog1"]').on("click", function () {
//Seleccionar la fila
$(this).closest("tr").siblings().removeClass("selectedRow");
$(this).parents("tr").toggleClass("selectedRow", this.clicked);
Ventana.dialog({
autoOpen: true,
modal: true,
height: 400,
width: 400,
title: "Builder",
buttons: {
"Add": function () {
txtCondi.val($("#condition").val());
txtVarlorV.val($("#returnValue").val());
$("#condition").val("");
$("#returnValue").val("");
$(this).dialog("destroy");
},
Cancel: function () {
//dialogFormValidator.resetForm();
$(this).dialog("destroy")
}
},
close: function () {
$("#condition").val("");
$("#returnValue").val("");
$(this).dialog("destroy")
}
});
return false;
});
$("table.order-list").append(newRow);
counter++;
$("button, input:submit, input:button").button();
$('input:text').addClass("ui-widget ui-state-default ui-corner-all");
});
$("table.order-list").on("click", "#ibtnDel", function (event) {
$(this).closest("tr").remove();
});
$("#btnEnviar").click(function () {
//Armo el objeto que servira de parametro, para ello utilizo una libreria JSON
//Este parametro mapeara con el definido en el WebService
var params = new Object();
params.Expresiones = armaObjeto();
$.ajax({
type: "POST",
url: "Default.aspx/Mostrar",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
loadMenuVar(data);
}
},
error: function (request, status, error) {
alert(jQuery.parseJSON(request.responseText).Message);
}
});
});
$(".showDialog").click(function () {
Ventana.dialog({
autoOpen: true,
modal: true,
height: 400,
width: 400,
title: "Constructor",
buttons: [
{ text: "Submit", click: function () { doSomething() } },
{ text: "Cancel", click: function () { $(this).dialog("destroy") } }
],
close: function () {
$(this).dialog("option", "autoOpen", false);
$(this).dialog("destroy")
}
});
return false;
});
});
This is the closest I've been able to get to the solution, but still can't get the dialog to remain hidden until a input is clicked
Any advise or guidance would be greatly appreciated.
P.S. Sorry for my bad english
I suspect it's because you're using destroy() rather than close() on the dialog. At the moment it looks like you're creating and destroying the dialog each time, don't do that. You should create the dialog once, isolate the dialog functionality to a separate function, and then just use open() and close() on it (you'll have to do some extra work to get the values into the right fields).
You can make your current code work if you style the dialog as hidden it'll stop happening, add this to your HTML (in the <HEAD>):
<style>
#dialog-form {
display: none;
}
</style>
you should probably have a separate style-sheet file you include that has that style in it. Similarly you should put all your JS in a separate file if it isn't already.
But I'd definitely look at re-writing the whole thing to follow the guidelines above, it does look like it can be made a lot simpler which makes it easier to support in the future.
EDIT
This is a simplified version that shows how I would do it.
Script:
var counter = 1; // Counter for number of rows
var currentRow = null; // Current row selected when dialog is active
// Create the dialog
$("#dialog-form").dialog({
autoOpen: false,
dialogClass: "no-close", // Hide the 'x' to force the user to use the buttons
height: 400,
width: 400,
title: "Builder",
buttons: {
"OK": function(e) {
var currentElem = $("#"+currentRow); // Get the current element
currentElem.val($("#d_input").val()); // Copy dialog value to currentRow
$("#d_input").val(""); // Clear old value
$("#dialog-form").dialog('close');
},
"Cancel": function(e) {
$("#d_input").val(""); // Clear old value
$("#dialog-form").dialog('close');
}
}
});
// This function adds the dialog functionality to an element
function addDialog(elemId) {
elem = $("#"+elemId);
elem.on('click', function() {
currentRow = $(this).attr('id');
$("#dialog-form").dialog('open');
});
}
// Add functionality to the 'add' button
$("#addRow").on('click', function () {
counter = counter + 1;
var newId = "in"+counter;
var newRow = "<tr><td><input id='"+newId+"' class='showDialog'></td></tr>";
$('TBODY').append(newRow);
// add the dialog to the new element
addDialog(newId);
});
// add the dialog to the first row
addDialog("in1");
HTML:
<div>
<fieldset>
<legend>Expression Builder</legend>
<table id="myTable" class="order-list">
<tbody><tr>
<td><input id='in1' class='showDialog'></td>
</tr>
</tbody>
</table>
<input type='button' id='addRow' value='add'></input>
</fieldset>
<br />
<input type="button" id="btnEnviar" value="Send" />
</div>
<div id="dialog-form" title="Add New Detail">
<input type="text" id="d_input" />
</div>
Fiddle
This isolates the different functionality into different functions. You can easily expand it to do what you want. If you want the remove functionality I'd consider having a remove button for every row with a given class with a trigger function that removes that row (and the button). Then have a separate count of active rows. At the start use disable() to disable the single button, when you add a row enable() all the buttons of that class. When you remove a row then disable the buttons is existingRows <= 1.

How to add a jquery dialog for each row in a html table?

I'm trying to add a jQuery dialog in each row of a table, using jQuery, and dataTables plugin.
I want to add in the dialog data specific to each row.
I've seen in other post that you can think of two ways:
1) One dialog for each row.
2) Only one dialog for all the rows, and then fill it with specific data.
In this example, I have a list of courses in a table, with name(nombre), code(codigo), and mode(modo).
For each row, there is a button (modificar) that should show a dialog to edit the data for that course. Of course, in each dialog, must be loaded the data of that row.
My idea (viewed other ideas in other post) is to put the dialog inside the row, so I can load the data from that row.
I created a class (masInfo) and in the Javascript code, I put a function that should open the dialog after the button is. But it doesn't work.
Do you have any idea? Thanks.
HTML Y JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link type="text/css"
href="css/milk.css" rel="stylesheet" />
<title>Paginadores tablas</title>
</head>
<body>
<%
CatalogoCursos catalogoCursos = CatalogoCursos.getCatalogoCursos();
ArrayList<Curso> cursos = catalogoCursos.getCursos();
%>
<div id="miTabla">
<form id="formulario" name="formulario" method="post">
<table id="tabla">
<thead>
<tr>
<th>Nombre </th>
<th>Código </th>
<th>Modo de juego </th>
<th> Acción </th>
</tr>
</thead>
<tbody>
<%
for(Curso curso: cursos) {
%>
<tr>
<td><%=curso.getNombre()%></td>
<td><%=curso.getCodigo()%></td>
<td><%=curso.getStringModo()%></td>
<td>
<input type="button" class="masInfo" value="modificar"/>
<div title="Modificar curso">
<table>
<tr>
<td><input type="text" name="mod_nombre" value="<%=curso.getNombre()%>"/></td>
<td><input type="text" name="mod_codigo" value="<%=curso.getCodigo()%>"/></td>
<td><input type="text" name="mod_modo" value="<%=curso.getStringModo()%>"/></td>
</tr>
</table>
</div>
</td>
</td>
</tr>
<%
}
%>
</tbody>
</table>
</form>
</div>
</body>
</html>
JAVASCRIPT
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.custom.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript">
(function($) {
// Dialog
$('.masInfo').next().dialog({
autoOpen: false,
width: 600,
buttons: {
"Borrar": function() {
document.formulario.submit();
$(this).dialog("close");
},
"Cancelar": function() {
$(this).dialog("close");
}
}
});
// Dialog Link
$('.masInfo').click(function(){
$('#dialog').dialog('open');
return false;
});
});
You are much better off using just one dialog and populate the relevant information in the dialog on the button click. The way you currently do it will result in a lot of duplicated input elements.
So, the HTML would look like:
<div id="miTabla">
<table id="tabla">
<thead>
<tr>
<th>Nombre </th>
<th>Código </th>
<th>Modo de juego </th>
<th> Acción </th>
</tr>
</thead>
<tbody>
<%
for(Curso curso: cursos) {
%>
<tr>
<td><%=curso.getNombre()%></td>
<td><%=curso.getCodigo()%></td>
<td><%=curso.getStringModo()%></td>
<td>
<input type="button" class="masInfo" value="modificar"/>
</td>
</td>
</tr>
<%
}
%>
</tbody>
</table>
</div>
<div title="Modificar curso" id="ModificarDialog">
<form id="formulario" name="formulario" method="post">
<table>
<tr>
<td><input type="text" name="mod_nombre" id="mod_nombre" /></td>
<td><input type="text" name="mod_codigo" id="mod_codigo" /></td>
<td><input type="text" name="mod_modo" id="mod_modo" /></td>
</tr>
</table>
</form>
</div>
​​​
JavaScript would change to:
(function($) {
// Dialog
$('#ModificarDialog').dialog({
autoOpen: false,
width: 600,
buttons: {
"Borrar": function() {
document.formulario.submit();
$(this).dialog("close");
},
"Cancelar": function() {
$(this).dialog("close");
}
}
});
// Dialog Link
$('.masInfo').click(function(){
var cells = $(this).parent().find('td');
$('#mod_monbre').val(cells.eq(0).text());
$('#mod_codigo').val(cells.eq(1).text());
$('#mod_modo').val(cells.eq(2).text());
$('#dialog').dialog('open');
return false;
});
});​

create div dynamically on click of a hyperlink in asp.net mvc

1.I want to dynamically generate div containing textbox with unique id on click of button
<input id="<%:rid %>" type="button" value="reply"/>
2.I also want to use jquery ajax mathod to carry the textbox data to ashx file .
Can anyone help me
code
var lineItemCount = 0;
$(document).ready(function () {
$(".commentbox input[type='button']").click(function () {
var id = $(this).attr("id");
alert(id);
var cid = id.substring(5);
var containerid = "container" + cid;
alert(containerid);
//Increase the lineitemcount
lineItemCount++;
//Add a new lineitem to the container, pass the lineItemCount to makesure
getLineItem()
// can generate a unique lineItem with unique Textbox ids
$(containerid).append(getLineItem(lineItemCount));
});
});
//Create a new DIV with Textboxes
function getLineItem(number) {
var div = document.createElement('div');
//Give the div a unique id
div.setAttribute('id', 'lineitem_' + number);
//pass unique values to the getTextbox() function
var t1 = getTextbox('txt_' + number + '_1');
div.appendChild(t1);
return div;
}
//Create a textbox, make sure the id passed to this function is unique...
function getTextbox(id) {
var textbox = document.createElement('input');
textbox.setAttribute('id', id);
textbox.setAttribute('name', id);
return textbox;
}
iteration through model in aspx page
<%var i=1;%>
<%foreach (var commentitem in item.commentsModelList)
{
<table border="0" class="commentbox">
<tr>
<%var rid = "reply" + i;%>
<div id="<%:containerid %>">
<td> <input id="<%:rid %>" type="button" value="reply"/>
</div>
</td>
</tr>
</table>
<% i++;}%>
I changed your markup little bit to get the corresponding id of items on my click events
HTML
<table border="0" class="commentbox">
<tr>
<td>Some Item text
</td>
</tr>
<tr>
<td>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
</table>
And the Script
$(function(){
$(".commentbox .btnReply").click(function(){
$(this).hide();
var id=$(this).attr("id").split("-")[1]
var strDiv="<input type='text' class='txtCmnt' id='txtReply-"+id+"' /> <input type='button' class='btnSave' value='Save' id='btnSave-"+id+"' /> ";
$("#container-"+id).html(strDiv);
});
$(".commentbox").on("click",".btnSave",function(){
var itemId=$(this).attr("id").split("-")[1]
var txt=$(this).parent().find(".txtCmnt").val();
$.post("/echo/json/", {reply: txt, id: itemId},function(data){
alert(data);
//do whatever with the response
})
});
});
Here is the jsfiddle example : http://jsfiddle.net/UGMkq/30/
You need to change the post target url to your relevant page which handles the ajax response.
EDIT : As per the comment about handing Multiple Divs
As long as you have the container div ids unique, it will work, I just changed the markup to include more than one item.
<table border="0" class="commentbox">
<tr>
<td>Some Item text<br/>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
<tr>
<td>Some Another Content here <br/>
<div id="container-2" ></div>
<input type="button" class='btnReply' id="reply-2" value="Reply" />
</td>
</tr>
</table>
Here is the sample :http://jsfiddle.net/UGMkq/44/
For the above output to be rendered, you probably want to write your razor syntax like this
<table border="0" class="commentbox">
#foreach (var commentitem in item.commentsModelList)
{
<tr>
<td>Some Another Content here<br/>
<div id="container-#(commentitem.Id)" ></div>
<input type="button" class='btnReply' id="reply-#(commentitem.Id)" value="Reply" />
</td>
</tr>
}
</table>
Instead of creating a new table for each item, I created a new row in existing table.

Resources