jquery / Ajax "undefined" error - asp.net-mvc

i am trying to get an image uploader working inside my MVC project, but everytime i click the upload file button, i get "Error undefined", i am not sure where i am going wrong.
The page is a partial view, loaded inside a #Html.BeginForm . below is the code i am using.
Index.cshtml
#using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="container">
<div class="row">
<article class="col-sm-12 col-md-12 col-lg-12 sortable-grid ui-sortable">
<div id="wid-id-0">
<!-- widget div-->
<div role="content">
<!-- widget content -->
<div class="widget-body">
<div class="row" style="background: white">
<form id="wizard-1" novalidate="novalidate">
<div id="bootstrap-wizard-1" class="col-sm-12">
<div class="tab-content">
#*Tab 1 (Step 1)*#
<div class="tab-pane active" id="tab1">
<br>
#Html.Partial("Registration/_Step1")
<div class="form-actions">
<div class="row">
<div class="col-sm-12">
<ul class="pager wizard no-margin">
<li class="previous disabled">
Previous
</li>
<li data-target="#step2" class="next">
Next
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="form-bootstrapWizard">
<ul class="bootstrapWizard form-wizard" style="background: coral">
<li class="active" data-target="#step1">
<span class="step">1</span> <span class="title">Step 1: Profile Information</span>
</li>
<li data-target="#step2" class="">
<span class="step">2</span> <span class="title">Step 2: Profile Picture</span>
</li>
<li data-target="#step3" class="">
<span class="step">3</span> <span class="title">Step 3: Identification</span>
</li>
<li data-target="#step4">
<span class="step">4</span> <span class="title">Step 4: Submit Profile</span>
</li>
</ul>
<div class="clearfix"></div>
</div>
</div>
</form>
</div>
</div>
<!-- end widget content -->
</div>
<!-- end widget div -->
</div>
<!-- end widget -->
</article>
</div>
</div>
}
_Step1.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '#Url.Action("UploadFiles", "Account")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("error: " + error.statusMessage);
}
});
});
});
</script>
<table align="center">
<tr>
<td style="text-align: center;"><label>Upload Profile Picture</label></td>
<td></td>
</tr>
<tr>
<td valign="top"><img id="imgPreview" src="~/Content/Images/upload_holder.PNG" class="img-holder" style="width: 180px; height: 180px;" /></td>
<td>
#*<input type="submit" class="btn btn-lg" style="width: 200px; background: #0091d9; color: white;" value="Upload Photo" />*#
#*<input id="input-4" name="input4[]" type="file" multiple class="file-loading" style="width: 200px; background: #0091d9; color: white;" value="Upload Photo">*#
<input type="file" id="FileUpload" multiple />
<input type="submit" id="Upload" value="Upload"/>
<br />
<br />
<label>Acceptable file formats: jpg, gif or png file</label>
<br />
<label>Under 1 MB</label>
</td>
</tr>
</table>
any help is greatly appreciated!
EdIT: Below is the controller function, but its never hit.
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

Related

How to Save records to Master-detail tables in ASP.NET MVC 5

I have Test and Deta(Details) table in DB. With Entity Framework 5 I have obtained a model so I have classes generated from it. I also created controllers and views for the Deta table. I can add, clear and delete the records before saving but finally, I can't to save the records.
Test table has
(TestID,
MissionCode,
StartDate,
EndDate)
Deta table has
(DetaId,
TestType,
TestDate,
Driver,
Place,
TestID)
I used the following script in the view to add, clear and save the record.
#section scripts{
<script>
//Show Modal.
function addNewDeta() {
$("#newDetaModal").modal();
}
//Add Multiple Order.
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#testType").val()) == "" || $.trim($("#testDate").val()) == "" || $.trim($("#driver").val()) == "" || $.trim($("#place").val()) == "") return;
var testType = $("#testType").val(),
testDate = $("#testDate").val(),
driver = $("#driver").val(),
place = $("#place").val(),
detailsTableBody = $("#detailsTable tbody");
var tstItem = '<tr><td>' + testType + '</td><td>' + testDate + '</td><td>' + driver + '</td><td>' + place + '</td><td><a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(tstItem);
clearItem();
});
//After Add A New Order In The List, Clear Clean The Form For Add More Order.
function clearItem() {
$("#testType").val('');
$("#testDate").val('');
$("#driver").val('');
$("#place").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove It.
$(document).on('click', 'a.deleteItem', function (e) {
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "#ff6347").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveDeta(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Detas/SaveDeta",
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveDeta").click(function (e) {
e.preventDefault();
var detaArr = [];
detaArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
detaArr.push({
testType: $(this).find('td:eq(0)').html(),
testDate: $(this).find('td:eq(1)').html(),
driver: $(this).find('td:eq(2)').html(),
place: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
missionCode: $("#missionCode").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
deta: detaArr
});
$.when(saveDeta(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
}
This is the controller
namespace WebApplication2.Controllers
{
public class DetasController : Controller
{
ETHADAMISEntities db = new ETHADAMISEntities();
public ActionResult Index()
{
List<Test> DetaAndTest = db.Tests.ToList();
return View(DetaAndTest);
}
public ActionResult SaveDeta(string missionCode, DateTime startDate, DateTime endDate, Deta[] deta)
{
string result = "Error! Test Detail Is Not Complete!";
if (missionCode != null && startDate != null && endDate != null && deta != null)
{
var tstId = Guid.NewGuid();
Test model = new Test
{
TestID = tstId,
MissionCode = missionCode,
StartDate = startDate,
EndDate = endDate
};
db.Tests.Add(model);
foreach (var item in deta)
{
var id = Guid.NewGuid();
Deta O = new Deta
{
DetaId = id,
TestType = item.TestType,
TestDate = item.TestDate,
Driver = item.Driver,
Place = item.Place,
TestID = tstId
};
db.Detas.Add(O);
}
db.SaveChanges();
result = "Success! Test with Detail Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
This is the view
#model IEnumerable<WebApplication2.Models.Test>
<br /><br />
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<h2 class="panel-title pull-left" style="margin-left:10px;">
<strong>Test Details</strong>
</h2>
<button style="margin-right:10px" class="btn btn-primary pull-right" onclick="addNewDeta()">New Test</button>
</div>
</div>
#*Receive All Database Data From Controller And Display Those Data In Client Side*#
#if (Model.Count() != 0)
{
foreach (var item in Model)
{
<div class="panel-body">
<table class="table table-striped table-responsive">
<tbody>
<tr>
<td>Mission Code : #item.MissionCode </td>
<td>Start Date : #item.StartDate </td>
<td>End Date : #item.EndDate</td>
</tr>
<tr>
<td colspan="3">
<table class="table table-bordered">
<tbody>
<tr>
<th>Test Type</th>
<th>Test Date</th>
<th>Driver</th>
<th>Place</th>
</tr>
#foreach (var deta in item.Detas)
{
<tr>
<td>#deta.TestType</td>
<td>#deta.TestDate</td>
<td>#deta.Driver</td>
<td>#deta.Place</td>
</tr>
}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
}
}
else
{
<div class="panel-body">
<h3 style="color:red;">Empty!</h3>
</div>
}
</div>
#*Desing Bootstrap Modal With Order Form*#
<div class="modal fade" id="newDetaModal">
<div class="modal-dialog modal-lg" style=" width: 900px !important;">
<div class="modal-content">
<div class="modal-header">
×
<h4>Add New Test</h4>
</div>
<form id="NewDetailForm">
<div class="modal-body">
#*Test Details*#
<h5 style="color:#ff6347">Tests</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="TestID" />
<div class="form-group">
<label class="control-label col-md-2">
Mission Code
</label>
<div class="col-md-4">
<input type="text" id="missionCode" name="missionCode" placeholder="Mission Code" class="form-control" />
</div>
<label class="control-label col-md-2">
Start Date
</label>
<div class="col-md-4">
<input type="text" id="startDate" name="startDate" placeholder="Start Date" class="form-control" />
</div>
<label class="control-label col-md-2">
End Date
</label>
<div class="col-md-4">
<input type="text" id="endDate" name="endDate" placeholder="End Date" class="form-control" />
</div>
</div>
</div>
#*Test Detail Details*#
<h5 style="margin-top:10px;color:#ff6347">Test Details</h5>
<hr />
<div class="form-horizontal">
<input type="hidden" id="DetaId" />
<div class="form-group">
<label class="control-label col-md-2">
Test Type
</label>
<div class="col-md-4">
<input type="text" id="testType" name="testType" placeholder="Test Type" class="form-control" />
</div>
<label class="control-label col-md-2">
Test Date
</label>
<div class="col-md-4">
<input type="datetime" id="testDate" name="testDate" placeholder="Test Date" class="form-control" />
</div>
<label class="control-label col-md-2">
Place
</label>
<div class="col-md-4">
<input type="text" id="place" name="place" placeholder="Place" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">
Driver
</label>
<div class="col-md-4">
<input type="text" id="driver" name="driver" placeholder="Driver" class="form-control" />
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">AddToList</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead>
<tr>
<th style="width:30%">Test Type</th>
<th style="width:20%">Test Date</th>
<th style="width:25%">Driver</th>
<th style="width:15%">Place</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveDeta" type="submit" class="btn btn-success">Save Test Detail</button>
</div>
</form>
</div>
</div>
</div>

How to disable buttons based on data model values?

I am building a mini online shopping CMS project for collage.
I finished the project and now I want to add a feature where I have limited quantity of products.
When the quantity is equal to 0 then product is shown as 'out of stock' and my 'Add to cart' button becomes disabled.
I have added a 'quantity' property to my product class and now I need to change something in the Index view of the product.
I tried few options and it does not seem to work.
Here is the code for the Index.cshtml page.
#model IEnumerable
<Product>
#{ ViewData["Title"] = "Products"; }
<h1 class="display-4 pb-5">All Products</h1>
<div class="row">
#foreach (var item in Model)
{
<div class="col-4">
<div class="ajaxbg d-none">
<img src="~/Images/ajax_loader.gif" />
<p class="lead alert alert-success text-center d-none">
The product has been added!
</p>
</div>
<img src="~/Media/Products/#item.Image" class="img-fluid" alt="" />
<h4>#item.Name</h4>
<div>
#Html.Raw(item.Description)
</div>
<p>
#item.Price.ToString("C2")
</p>
<p>
<a asp-controller="Cart" asp-action="Add" asp-route-id="#item.Id" data-id="#item.Id" id="addToCartButton" class="btn btn-primary addToCart">Add to cart</a>
</p>
#if (item.Quantity == 0) { }
</div>
}
#if (ViewBag.TotalPages > 1) {
<div class="d-flex w-100 justify-content-center">
<pagination page-count="#ViewBag.TotalPages" page-target="/products" page-number="#ViewBag.PageNumber" page-range="ViewBag.PageRange"></pagination>
</div>
}
</div>
#section Scripts {
<script>
function DisableBtn() {
document.getElementById("addToCartBUtton").disabled = true;
}
$(function() {
$("a.addToCart").click(function(e) {
e.preventDefault();
let ajaxDiv = $(this).parent().parent().find("div.ajaxbg");
ajaxDiv.removeClass("d-none");
let id = $(this).data("id");
$.get('/cart/add/' + id, {}, function(data) {
$("div.smallcart").html(data);
ajaxDiv.find("img").addClass("d-none");
ajaxDiv.find("p").removeClass("d-none");
setTimeout(() => {
ajaxDiv.animate({
opacity: 0
}, function() {
$(this).addClass("d-none").fadeTo(.1, 1);
$(this).find("img").removeClass("d-none");
$(this).find("p").addClass("d-none");
});
});
});
});
});
</script>
}
Try this
#If(Model!=null)
{
#foreach (var item in Model)
{
..........
<p>
#if (item.Quantity == 0) {
<a disabled class="btn btn-primary addToCart">Add to cart</a>
}
else
{
<a asp-controller="Cart" asp-action="Add" asp-route-id="#item.Id" data-id="#item.Id" id="addToCartButton" class="btn btn-primary addToCart">Add to cart</a>
}
</p>
}
}

MVC Project memory leaking, how to fix it?

I've tried everything about that but i couldnt find a solution. On local, there's no problem. But when i publish to provider hosting. Memory leaking issue is coming out and IIS Recylcling every 75 seconds. I Used memory profiler but, no issue on local like i said. Here's my basecontroller code. Can it cause a memory leak?. And i use tags in layout. Maybe it causes a memory leak. If you want layout code i can add. For now, my basecontroller code be like;
public class BaseController : Controller
{
public BaseController()
{
GC.Collect(2, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
}
internal void ShowErrorMessage(string message)
{
ViewBag.ErrorMessage = message;
}
public List<Categories> GetCategories()
{
var catserv = new CategoryService();
return catserv.GetAll().Where(x => x.Status == DataStatus.Active).ToList();
}
public List<Products> GetProducts()
{
var prodserv = new ProductService();
return prodserv.GetAll().ToList();
}
public bool CheckAdmin()
{
string username = User.Identity.Name;
var member = new MemberService();
var result = member.GetUserName(username);
if (result.Data.IsAdmin != 1)
return false;
else
return true;
}
public string SamePath()
{
return Request.UrlReferrer.PathAndQuery.ToString();
}
}
GetCategories method is being used for layout. I couldnt add viewmodel entity and i added this method below.
Check my admincontroller and layout.
[HttpPost]
public ActionResult Login(Member memb)
{
var memberservice = new MemberService();
var getMemberResult = memberservice.Auth(memb.UserName, memb.Password);
if (getMemberResult.HasError)
{
ViewBag.mesaj = getMemberResult.ResultMessage;
return View();
}
if (getMemberResult.Data.Status == DataStatus.Banned)
{
return RedirectToAction("BannedUser");
}
FormsAuthentication.SetAuthCookie(getMemberResult.Data.UserName, false);
return RedirectToAction("Anasayfa", "Magaza");
}
And my layout.. and actually it has var baseController = ViewContext.Controller as web2.Controllers.BaseController; on the top
<body>
<div class="banner_bg_main">
<!-- header top section start -->
<div class="container">
<div class="header_section_top">
<div class="row">
<div class="col-sm-12">
<div class="custom_menu">
<ul>
<li>Kusursuz Tasarım</li>
<li>Profesyonel Çalışmalar</li>
<li>Uygun Fiyat Politikası</li>
<li>Promosyon Ürünleri</li>
<li>Matbaa Ürünleri</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- header top section start -->
<!-- logo section start -->
<div class="logo_section">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="logo"></div>
</div>
</div>
</div>
</div>
<!-- logo section end -->
<!-- header section start -->
<div class="banner_section layout_padding">
<div class="container">
<div id="my_slider" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<div class="row">
<div class="col-sm-12">
<h1 class="banner_taital">%100<br>Fiyat Garantisi</h1>
<div class="buynow_bt">Sipariş Ver</div>
</div>
</div>
</div>
<div class="carousel-item">
<div class="row">
<div class="col-sm-12">
<h1 class="banner_taital">Hemen Ürün<br>Siparişinizi Verin</h1>
<div class="buynow_bt">Sipariş Ver</div>
</div>
</div>
</div>
<div class="carousel-item">
<div class="row">
<div class="col-sm-12">
<h1 class="banner_taital">Tamamen isteğe<br>UYGUN TASARIM</h1>
<div class="buynow_bt">Sipariş Ver</div>
</div>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#my_slider" role="button" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a class="carousel-control-next" href="#my_slider" role="button" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
<div class="header_section pb-3">
<div class="container">
<div class="containt_main justify-content-center">
<div id="mySidenav" class="sidenav">
×
<a href=#Url.Action("Anasayfa","Magaza")>Anasayfa</a>
<a href=#Url.Action("Urunler","Magaza")>Ürünler</a>
#if (User.Identity.IsAuthenticated)
{
<a href=#Url.Action("Menu","Admin")>Admin Menü</a>
}
</div>
</div>
<div class="containt_main">
<span class="toggle_icon" onclick="openNav()"><img src="~/Content/images/toggle-icon.png"></span>
<div class="main">
<!-- Another variation with a button -->
#using (Html.BeginForm("Urunler", "Magaza", FormMethod.Get))
{
<div class="input-group">
#Html.TextBox("Ara", "", new { #class = "form-control", #placeholder = "Ürün Arayın", #type = "text" })
<div class="input-group-append">
<button class="btn btn-secondary" type="submit" style="background-color: #f26522; border-color:#f26522">
<i class="fa fa-search"></i>
</button>
</div>
</div>
}
</div>
<div class="header_box">
<div class="login_menu">
<!--<ul>
<li><a href="#">
<i class="fa fa-shopping-cart" aria-hidden="true"></i>
<span class="padding_10">Cart</span></a>
</li>
<li><a href="#">
<i class="fa fa-user" aria-hidden="true"></i>
<span class="padding_10">Cart</span></a>
</li>
</ul> -->
</div>
</div>
</div>
<div class="text-center mt-3">
<button class="btn btn-secondary dropdown-toggle mb-3" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Kategoriler
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#foreach (var item in baseController.GetCategories())
{
<a class="dropdown-item" href="#Url.Action("Urunler","Magaza", new {#kategori = item.Id })">#item.CategoryName</a>
}
</div>
</div>
</div>
</div>
<!-- header section end -->
<!-- banner section start -->
<!-- banner section end -->
</div>
#RenderBody()
<div class="footer_section layout_padding">
<div class="container">
<div class="footer_logo"><img style="height:100px;" src="~/Content/img/logo.png"></div>
<div class="footer_menu">
<ul>
<li>
<li>Uygun Fiyat Politikası</li>
<li>%100 Memnuniyet</li>
</ul>
<br />
<ul>
<li>Anasayfa</h3></li>
</ul>
<br />
<ul>
<li><h3 style="color:white">Adres</h3>Rami Cuma Mah.<br /> Oruç Sk. No:20B<br />Eyüp/İstanbul</li>
</ul>
</div>
<div class="location_main">Whatsapp Hattı İçin Tıkla</div>
<div class="location_main"><img class="img-responsive" style="height:55px;" src="~/Content/img/instalogo.png" /></div>
</div>
</div>
<script src="~/Content/js/jquery.min.js"></script>
<script src="~/Content/js/bootstrap.bundle.min.js"></script>
<script src="~/Content/js/jquery-3.0.0.min.js"></script>
<script src="~/Content/js/plugin.js"></script>
<!-- sidebar -->
<script src="~/Content/css/jquery.mCustomScrollbar.concat.min.js"></script>
<script src="~/Content/css/custom.js"></script>
<script type="text/javascript" src="~/Content/js/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10"charset="utf-8"></script>
<script>
var counter = 0;
function openNav() {
counter++;
if (counter % 2 == 1)
document.getElementById("mySidenav").style.width = "250px";
else
document.getElementById("mySidenav").style.width = "0";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>
#if (ViewBag.ErrorMessage != null || TempData["Fail"] != null)
{
<script>
swal.fire({
title: "Olmadı be",
text: '#ViewBag.ErrorMessage',
icon: "error",
});
</script>
}
#if (ViewBag.successtoindex != null)
{
<script>
swal.fire({
icon: 'info',
title: 'Hadi Anasayfaya Dönelim',
text: '#ViewBag.successtoindex',
button: 'Hadi Anasayfaya Dönelim!'
}).then(function () {
window.location = "/";
});
</script>
}
#if (ViewBag.success != null || TempData["Success"] != null)
{
<script>
swal.fire({
title: "Mükemmel",
text: '#ViewBag.success',
icon: "success",
button: "Aww yiss!",
});
</script>
}
#if (ViewBag.successadminmenu != null)
{
<script>
swal.fire({
title: "Başarılı",
text: '#ViewBag.successadminmenu',
icon: "success",
button: "Muhteşem!",
}).then(function () {
window.location = "menu";
});;
</script>
}

Why does the clone remove method doesn't work after the function was altered?

I have been trying to delete specific clone data using JQuery -UI. i had to change my functions recently since then the remove button doesn't work. Please help me find my error.
My whole function that includes, Multidimensional Arrays along with form cloning! check out my remove function which i think has no problem in it.
$(function() {
var questionHolder = $('.question').clone(true);
$("#addQuestion").on('click', function(e) {
e.preventDefault();
var str = $("p.number:last").text(),
newValue = parseInt(str, 10) + 1;
var newQ = questionHolder.clone();
newQ.find('input, textarea')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]/, '[' + newValue + ']');
})
.end()
.find('.number')
.html(newValue)
.end()
.appendTo('#questioncontainer')
.after('<br><button class="addQuestion_delete btn btn-danger" type="button">Remove Parent Clone</button><br>');
$(".addQuestion_delete").click(function(e) {
$(this).closest("#questioncontainer").remove();
e.preventDefault();
});
});
$('body').on('click', '.addAnswer', function(e) {
e.preventDefault();
var group = $(this).parent();
parent = $(this).parent().parent();
group.find(".answer:last")
.clone(true)
.find('input, textarea')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]$/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
});
})
.end()
.appendTo(
group.find('.answerContainer'))
.after('<button class="addAnswer_delete btn btn-danger" type="button"><i class="fa fa-minus"></i>Remove Child clone</button><br><br><br>');
$(".addAnswer_delete").click(function(e) {
$(this).closest(".answerContainer").remove();
e.preventDefault();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- parent container -->
<div id="questioncontainer">
<!-- parent that clones -->
<div style="border:1px solid black; width:400px; padding:20px; margin-bottom:10px;" class="question border p-5 mt-3 shadow">
<!-- clone items inputs/textareas/files -->
<div class="row">
<div class="col-lg-6">
<!-- Educational Institute -->
<input oninput="checkCompany()" id="company" name="employer[1]" type="text" class="input-form track track_exp_qua" data-score=20>
<span class="bar"></span>
<label class="input-label"> Company <span id="text" class="required"> </span></label>
<!-- Educational Institute -->
<p class="validate text-danger pt-2" id="company_error"></p>
</div>
<div class="col-lg-6">
<!-- Job title -->
<input oninput="checkJobTitle()" id="job_title" name="job_title[1]" type="text" class="input-form track track_exp_qua" data-score=10>
<span class="bar"></span>
<label class="input-label"> Job Title <span id="text" class="required"> </span></label>
<!-- Job title -->
<p class="validate text-danger pt-2" id="job_title_error"></p>
</div>
</div>
<div class="justify-content-center pb-4">
<h4>Below is the child clone</h4>
</div>
<!-- child container -->
<div style="border:1px solid red; padding:20px;" class="answerContainer">
<div class="answer">
<div class="row">
<!-- best project url -->
<div class="col-lg-6">
<input name="best_project[1][1]" type="text" class="input-form track track_exp_qua" data-score=10>
<span class="bar"></span>
<label class="input-label">Best Project<small style="color:#FFBF00;"> (URL's Only) </small> <span id="text" class="optional"> </span></label>
</div>
<!-- best project url -->
</div>
<br>
</div>
</div>
<!-- clone items inputs/textareas/files end-->
<br>
<button class="addAnswer btn btn-info" href="#"><i class="fa fa-plus"></i> Add Child</button>
</div>
<!-- parent that clones end-->
</div>
<!-- parent container end -->
<br>
<button id="addQuestion" class="btn btn-success" href="#"> <i class="fa fa-plus"></i> Add Parent </button>
Some of your objects were too ambigous, so things were not going to work as you expected.
Consider the following example.
$(function() {
function updateName(i, n) {
i = $(i);
var o = i.attr("name");
if (n != undefined) {
i.attr("name", o.replace(/\[(\d+)\]/, '[' + n + ']'));
} else {
i.attr("name", o.replace(/\[(\d+)\]$/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
}));
}
return true;
}
function makeDel(cnt, pClass, tObj) {
return $("<button>", {
class: pClass + " btn btn-danger",
type: "button"
}).html(cnt).insertAfter(tObj);
}
function addQuestion(event) {
var self = $(event.target);
event.preventDefault();
var newValue = $(".question").length + 1;
var newQ = $(".question").eq(0).clone(true);
$("input, textarea", newQ).each(function() {
updateName(this, newValue);
});
newQ.appendTo("#questioncontainer");
var newD = makeDel("Remove Parent Clone", "addQuestion_delete", newQ);
newD.click(function(e) {
e.preventDefault();
newQ.remove();
$(this).remove();
});
}
function addAnswer(event) {
var self = $(event.target);
event.preventDefault();
var group = self.parent().find(".answerContainer");
var newA = $(".answer:last", group).clone(true);
$("input, textarea", newA).each(function() {
updateName(this);
});
newA.appendTo(group);
var newD = makeDel("<i class='fa fa-minus'></i> Remove Child clone", "addAnswer_delete", group);
newD.click(function(e) {
e.preventDefault();
newA.remove();
$(this).remove();
});
}
$("body").on("click", "#addQuestion", addQuestion);
$('body').on('click', '.addAnswer', addAnswer);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- parent container -->
<div id="questioncontainer">
<!-- parent that clones -->
<div style="border:1px solid black; width:400px; padding:20px; margin-bottom:10px;" class="question border p-5 mt-3 shadow">
<!-- clone items inputs/textareas/files -->
<div class="row">
<div class="col-lg-6">
<!-- Educational Institute -->
<input oninput="checkCompany()" id="company" name="employer[1]" type="text" class="input-form track track_exp_qua" data-score=20>
<span class="bar"></span>
<label class="input-label"> Company <span id="text" class="required"> </span></label>
<!-- Educational Institute -->
<p class="validate text-danger pt-2" id="company_error"></p>
</div>
<div class="col-lg-6">
<!-- Job title -->
<input oninput="checkJobTitle()" id="job_title" name="job_title[1]" type="text" class="input-form track track_exp_qua" data-score=10>
<span class="bar"></span>
<label class="input-label"> Job Title <span id="text" class="required"> </span></label>
<!-- Job title -->
<p class="validate text-danger pt-2" id="job_title_error"></p>
</div>
</div>
<div class="justify-content-center pb-4">
<h4>Below is the child clone</h4>
</div>
<!-- child container -->
<div style="border:1px solid red; padding:20px;" class="answerContainer">
<div class="answer">
<div class="row">
<!-- best project url -->
<div class="col-lg-6">
<input name="best_project[1][1]" type="text" class="input-form track track_exp_qua" data-score=10>
<span class="bar"></span>
<label class="input-label">Best Project<small style="color:#FFBF00;"> (URL's Only) </small> <span id="text" class="optional"> </span></label>
</div>
<!-- best project url -->
</div>
<br>
</div>
</div>
<!-- clone items inputs/textareas/files end-->
<br>
<button class="addAnswer btn btn-info" href="#"><i class="fa fa-plus"></i> Add Child</button>
</div>
<!-- parent that clones end-->
</div>
<!-- parent container end -->
<br>
<button id="addQuestion" class="btn btn-success" href="#"> <i class="fa fa-plus"></i> Add Parent </button>
Objects are created and referenced a bit better, so it's easier to manipulate them and remove them as needed. Anytime you are doing the same thing multiple times, you could consider creating a function for it.

Bootstrap : accordion-toggle doesn't work

I have a problem with my accodion-toggle . I put it in my code but it doesn't work my title stay in blue and with nothing near of my title.
This is my code :
#{string module_origine = "";
int step = 0;
}
<div class="accordion" id="accordion2">
#foreach (var test in Model)
{
if (module_origine != test.module)
{
module_origine = test.module;
step = step + 1;
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse_#step">
#Html.DisplayFor(ModelItem => test.module)
</a>
</div>
<div id="Collapse_#step" class="accordion-body collapse in">
<div class="accordion-inner ">
#foreach (var item in Model.Where(item => item.module == module_origine))
{
<form method="get" action="/#Html.DisplayFor(modelItem =>item.droit)">
<button type="submit" class="btn btn-primary" title="#Html.DisplayFor(ModelItem => item.description)">#Html.DisplayFor(modelItem => item.menunom)</button>
</form>
}
</div>
</div>
</div>
}
}
</div>
I don't understand why my class accordion-toggle doesn't work so I hope I can understand why and help me think you !
to get a panel it's easy just change that :
#{string module_origine = "";
int step = 0;
}
**<div class="panel-group" id="accordion">** //add that to create panel
#foreach (var test in Model)
{
if (module_origine != test.module)
{
module_origine = test.module;
step = step + 1;
<div class="panel panel-success ">
<div class="panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse_#step">
#Html.DisplayFor(ModelItem => test.module)
</a>
</div>
<div id="Collapse_#step" class="accordion-body collapse in">
<div class="accordion-inner ">
#foreach (var item in Model.Where(item => item.module == module_origine))
{
<form method="get" action="/#Html.DisplayFor(modelItem =>item.droit)">
<button type="submit" class="btn btn-primary" title="#Html.DisplayFor(ModelItem => item.description)">#Html.DisplayFor(modelItem => item.menunom)</button>
</form>
}
</div>
</div>
</div>
}
}
</div>
I just remove the accordion content it's not wooking on my thing

Resources