To make this code, you must construct several
javascript
one functions to add
input
, one to save and send
Server-Side
information, one to replace
input
with
span
and another to disappear with the button, I also made a cancel button if you want to cancel the action of creating a new email.
Minimum example:
Code of View
:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="form-group">
<button type="button" id="btnAddEmail">Adicionar</button>
<table id="tblEmails">
<thead>
<tr>
<td>#</td>
<td>Email</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@section scripts {
<script>
var isEmail = function (value)
{
var t = /^[a-z0-9.]+@@[a-z0-9]+\.[a-z]+\.([a-z]+)?$/i;
return t.test(value);
}
var uniqid = function () {
return (new Date().getTime()
+ Math.floor((Math.random() * 10000)
+ 1)).toString(16);
};
function addEmail()
{
var id = uniqid();
var u = 'txt' + id;
var t = 'tr' + id;
var s = '<tr id=\'' + t + '\'><td></td>';
s = s + '<td><input name="email" id="' + u + '" required></td>';
s = s + '<td class="bto">';
s = s + '<button type="button"
onclick="saveEmail(\'' + u + '\')">Salvar</button>';
s = s + '<button type="button"
onclick="cancelEmail(\'' + t + '\')">Cancelar</button>';
s = s + '</td ></tr>';
$("#tblEmails tbody").append(s);
}
function saveEmail(id) {
var obj = document.getElementById(id);
if (obj.value != "" && isEmail(obj.value)) {
$.post("@Url.Action("Create", "Emails")", { email: obj.value },
function (response) {
if (response.status) {
replaceLabelAndButton(obj);
}
}, 'json');
return true;
}
alert("Digite o e-mail corretamente");
obj.focus();
return false;
}
function cancelEmail(id) {
jQuery(document.getElementById(id)).remove();
}
function replaceLabelAndButton(obj) {
jQuery(obj)
.parent()
.next()
.html('');
jQuery(obj)
.parent()
.html('<span>' + obj.value + '</span>');
}
$(document).ready(function () {
$("#btnAddEmail").click(function () {
addEmail();
});
});
</script>
}
Code of Controller
:
In this code of controller
it is only to have the same name as the input
( which in the case was email ) to retrieve the information and thus make the write code. >
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication7.Controllers
{
public class EmailsController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult Create(string email)
{
var c = email;
return Json(new { status = true });
}
}
}