Dropzone inside Vue transition modal doesn´t work - javascript

i have a dropzone function in mounted function, it works fine when in the view the dropzone is outside of a modal, but in transition modal doesn´t work, any idea or solution for this?
this is .ftl
...
<transition name="modal" id="deletemo">
<div v-if="uploadModal" >
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">upload file</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #click="uploadModal = false">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>select file type</label>
<multiselect placeholder="Seleccione tipo de fichero" v-model="fileTypeSelected" :options="fileTypelist" > </multiselect>
</div>
<div class="form-group">
<div class="animated fadeIn">
<div class="card">
<div class="card-body">
<div id="uploadFile" class="dropzone col" style="border-style: dashed;">
<div class="dz-message" data-dz-message>
<div>upload file here ...</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" #click="uploadModal = false">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</transition>
.js
mounted: function () {
var vue = this;
dropzone.autoDiscover = false;
$("div#uploadFile").dropzone({
url: "/demo/uploadFile"
,acceptedFiles: ".pdf"
,clickable: false
,maxFilesize: 100
,addRemoveLinks: true
,init: function() {
this.on('success', function(file, json) {
});
this.on('addedfile', function(file) {
});
this.on("sending", function(file, xhr, formData) {
formData.append("nif", vue.filePerson);
});
this.on("complete", function(file) {
//this.removeFile(file);
});
}
});
}
});
I was looking for other similar post but not for a transition , so it does not work for me.
thanks in advance.

After trying multiple things i found the solution using an attribute "v-on:enter="enter" in transition and inside function initialize dropzone.
<transition name="modal" v-on:enter="enter" >
......
</transition>
enter: function () {
$("div#uploadFile").dropzone({
url: "/demo/uploadFile"
......
});
},

I have experienced the same issue. I this the problem is mostly the v-if div:
<div **v-if=**"uploadModal" >
<div id="uploadFile" class="dropzone col" style="border-style: dashed;">
<div class="dz-message" data-dz-message>
<div>upload file here ...</div>
</div>
</div>
</div>
VueJS seems to take control of everything happening there, to enable the dropzone, you will need to use #click or something to that effect. We just need to create the method that will be responsible for opening the FileInput:
methods: {
openDropZone() {
const dropzone = Dropzone.options.myDropzone = {
url: "http://localhost:8000/upload",
maxFiles : 2,
addRemoveLinks: true,
headers: {
"X-CSRFToken": "{{ csrf_token }}",
},
};
dropzone.hiddenInputFile.click();
}
}
Then we call the openDropZone() method from #click:
<div v-if="uploadModal" >
<div id="uploadFile" **#click="openDropZone()"** class="dropzone col" style="border-style: dashed;">
<div class="dz-message" data-dz-message>
<div>upload file here ...</div>
</div>
</div>
</div>

Related

Uncaught TypeError: Cannot read property '' of undefined using Laravel and AJAX

I have the following select box:
<select class="form-control select2-single" data-width="100%" name="numero_projet" id="numero_projet">
<option label=" "> </option>
#foreach($projets as $projet)
<option data-id="{{$projet->id_projet}}" value="{{$projet->id_projet}}">{{$projet->numero_projet}}</option>
#endforeach
</select>
And the following ajax code to get data :
<script>
$(document).ready(function(){
$('#numero_projet').change(function(){
var id_projet = $(this).find("option:selected").data("id");
console.log(id_projet);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url:"getProjet/"+id_projet,
type:"GET",
success:function(html){
var content = html.content;
$("div.name_casting").append(content.id_casting);
}
})
})
})
</script>
And the following controller:
public function getProjet()
{
if(request()->ajax())
{
$id_projet = request('numero_projet');
$projets_casting = Projet_Casting::where('id_projet',$id_projet)->get();
return response()->json(['projets_casting' => $projets_casting]);
}
}
And I have the following view where I should display the data that I get from controller:
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Select from Library</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#foreach($projets_casting as $projet_casting)
<div class="modal-body scroll pt-0 pb-0 mt-4 mb-4">
<div class="accordion" id="accordion">
<div class="mb-2">
<button class="btn btn-link p-0 folder-button-collapse" data-toggle="collapse"
data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<span class="icon-container">
<i class="simple-icon-arrow-down"></i>
</span>
<span class="folder-name">Castings</span>
</button>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="list disable-text-selection">
<div class="row">
<div class="col-6 mb-1 sfl-item-container casting"
data-preview-path="img/products/chocolate-cake-thumb.jpg"
data-path="img/products/chocolate-cake-thumb.jpg"
data-label="chocolate-cake-thumb.jpg">
<div class="card d-flex mb-2 p-0 media-thumb-container">
<div class="d-flex align-self-stretch">
<img src="img/products/chocolate-cake-thumb.jpg" alt="uploaded image"
class="list-media-thumbnail responsive border-0" />
</div>
<div class="d-flex flex-grow-1 min-width-zero">
<div
class="card-body pr-1 pt-2 pb-2 align-self-center d-flex min-width-zero">
<div class="w-100">
<p class="truncate mb-0">{{$projet_casting->id_casting}}</p>
</div>
</div>
<div
class="custom-control custom-checkbox pl-1 pr-1 align-self-center">
<label class="custom-control custom-checkbox mb-0">
<input type="checkbox" class="custom-control-input">
<span class="custom-control-label"></span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
<div class="modal-footer">
<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Annuler</button>
<button type="button" class="btn btn-primary sfl-submit">Selectionner</button>
</div>
</div>
</div>
It should display in this div the id_casting of each projects
<div class="w-100 name_casting">
<p class="truncate mb-0">ok</p>
</div>
But I get the following error:
Uncaught TypeError: Cannot read property 'id_casting' of undefined
What is wrong with my code?
Update
I have the following HTML in my view:
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="list disable-text-selection">
<div class="row">
<div class="col-6 mb-1 sfl-item-container casting"
data-preview-path="img/products/chocolate-cake-thumb.jpg"
data-path="img/products/chocolate-cake-thumb.jpg"
data-label="chocolate-cake-thumb.jpg">
<div class="card d-flex mb-2 p-0 media-thumb-container casting2">
<div class="d-flex align-self-stretch">
<img src="img/products/chocolate-cake-thumb.jpg" alt="uploaded image"
class="list-media-thumbnail responsive border-0" />
</div>
<div class="d-flex flex-grow-1 min-width-zero">
<div
class="card-body pr-1 pt-2 pb-2 align-self-center d-flex min-width-zero">
<div class="w-100 castings">
<p class="truncate mb-0">OK</p>
</div>
</div>
<div
class="custom-control custom-checkbox pl-1 pr-1 align-self-center">
<label class="custom-control custom-checkbox mb-0">
<input type="checkbox" class="custom-control-input">
<span class="custom-control-label"></span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And I'm trying the following script:
<script>
$(document).ready(function(){
$('#numero_projet').change(function(){
var id_projet = $(this).find("option:selected").data("id");
console.log(id_projet);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url:"getProjet/"+id_projet,
type:"GET",
dataType:"json",
success:function(json){
renderTemplate(json)
}
});
function renderTemplate(json) {
var content = ` <div">
<p class="truncate mb-0">${json.id_casting}</p>
</div>`;
$("div.name_casting").append(content);
}
})
})
</script>
But I have nothing. I have always OK and I have no error!
UPDATE2
Now I can get the data that I want, but I get multiple rows in the same time so I should having multiple divs in my HTML.
I'm getting the following result:
While I shoult get the 18 in a div and 19 in other div and not in the same place.
Analogous to #professor's answer:
Use the JSON (recommended)The Controller doesn't have to be modifiedIn your blade/JavaScript, change the following:
$.ajax({
url:"getProjet/"+id_projet,
type:"GET",
dataType:"json",
success:function(json){
renderTemplate(json)
}
});
function renderTemplate(json) {
var content = `<div>
${json.castings.map((casting) => casting.id_projet)}
</div>`;
$("div.name_casting").append(content);
}
Use the HTMLThe blade view and JavaScriptIn your controller, change the following:
public function getProjet()
{
if(request()->ajax())
{
$id_projet = request('numero_projet');
$projets_casting = Projet_Casting::where('id_projet',$id_projet)->get();
return view('your-view', ['projets_casting' => $projets_casting]);
}
}

MVC - Modal not displaying using AJAX

I am having trouble displaying information on my popup page. I created main view where the user clicks a card and it should trigger a modal to display required information (including partial view) through ajax, however that partial page should be displayed through a controller but the action result within a controller is not triggered at all despite the fact that I have specified the data-url withing my java-script function.
Here is my index page:
<div id="pageContainer">
<div class="container">
<!--Boxers Cards-->
<div class="row text-center default-div-top-padding">
<div class="col-lg-3 col-md-6 mb-4 rounded fighter-card" id="FighterDetails">
<a id="popup-button" data-url="#Url.Action("FighterDetails", "RankingsController")" data-toggle="modal" data-target=".fighter-modal">
<img class="card-img-top" src="http://nyfights.com/wp-content/uploads/2017/12/Screen-Shot-2017-12-11-at-5.10.25-PM.png" alt="" />
<div class="card-body fighter-card-body-color" style="border-bottom: 2px solid rgb(255, 172, 0)">
<div class="card-title fighter-card-title">Vasyl Lomachenko</div>
<ul class="fighter-card-information">
<li>
<div class="fighter-card-information-title">Belts: </div>
<div class="fighter-card-information">WBA, WBO, IBF, WBC</div>
</li>
<li>
<div class="fighter-card-information-title">Record:</div>
<div class="fighter-card-information">11-1-0 9KO</div>
</li>
</ul>
</div>
<div class="card-footer fighter-card-ranking-position fighter-card-footer-color">
<h1>1</h1>
</div>
<input type="hidden" name="popup=title" value="Fighter Details" />
</a>
</div>
</div>
<!--Boxers Cards End-->
</div>
</div>
<!--Modal-->
<div class="modal fade fighter-modal" role="dialog" aria-labelledby="gridSystemModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header blueBackground goldBorderBottom">
<button type="button" class="close" data-dismiss="modal" aria-label="close" data-toggle="tooltip" data-placement="left" title="close">
<span aria-hidden="true">
×
</span>
</button>
<span class="modal-title" id="gridSystemModalLabel"></span><br />
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="">
<div id="ajax-target-container"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
//AJAX Popup Control - Renders a popup with designed partial view
$("container").on("click", "#popup-button", function () {
//Set the URL
var url = $(this).attr('data-url');
//Set the title
var popupTitle = $(this).find($('input[name=popup-title]')).val();
$(".modal-title").text(popupTitle);
//Set a default spinner
$(".modal #ajax-target-container").append("<span class='blueText'><i class='fa fa-spinner fa-spin fa-3x fifteenPxSpacingRight'></i> Loading... </span>");
$.ajax({
type: "GET",
cache: false,
url: url,
success: function (data) {
$(".modal #ajax-target-container").empty();
$(".modal #ajax-target-container").html(data);
}
})
});
});
</script>
My Partial View:
<div class="row">
#using (Html.BeginForm("", "", FormMethod.Post, new { #id = "Fighter-Details" }))
{
#Html.AntiForgeryToken()
<div class="card-body fighter-card-body-color" style="border-bottom: 2px solid rgb(255, 172, 0)">
<div class="card-title fighter-card-title">Vasyl Lomachenko</div>
<ul class="fighter-card-information">
<li>
<div class="fighter-card-information-title">Belts: </div>
<div class="fighter-card-information">WBA, WBO, IBF, WBC</div>
</li>
<li>
<div class="fighter-card-information-title">Record:</div>
<div class="fighter-card-information">11-1-0 9KO</div>
</li>
</ul>
</div>
}
And my controller:
[HttpGet]
public PartialViewResult FighterDetails()
{
return PartialView("~/Views/Rankings/PartialViews/FighterDetails.cshtml");
}
Now when I click the card it will display only the top of the popup:
And that's it. Controller is not triggered at all so it's seems it is not going through the java script function but I'm not sure why.
Any help would be appreciated,
Thanks
In your JS code, it looks like you're missing the '.' before 'container' in the jQuery selector. Since 'container' is a class attribute, the proper jQuery selector is '.container'.
Try changing
$("container").on("click", "#popup-button", function () {
to
$(".container").on("click", "#popup-button", function () {

Accessing MVC Data Model properties in Angular JS

In My Angular UI Project , I want to show / hide three buttons based on the logged in User's Roles.
That I get in TabLevelSecurity.cs... is_approver field ... file via ...
public override void OnAuthorization(AuthorizationContext filterContext) {
try
{
IPrincipal p = HttpContext.Current.User;
string UsrName = string.Empty;
UsrName = p.Identity.Name;
if (UsrName.Contains("\\"))
{
int index = UsrName.IndexOf("\\");
UsrName = UsrName.Substring(index + 1);
}
//Tab level security configuration entries read from JSON file
List<Entities.TabLevelSecurityParams> listTabLevelSecurity = new List<Entities.TabLevelSecurityParams>();
string JsonDeserializeTabLevelUsers = File.ReadAllText(ConfigurationManager.AppSettings["TabLevelSecurityConfigPath"]);
listTabLevelSecurity = JsonConvert.DeserializeObject(JsonDeserializeTabLevelUsers, (typeof(List<Entities.TabLevelSecurityParams>))) as List<Entities.TabLevelSecurityParams>;
//Check if the use is authenticated
if (p.Identity.IsAuthenticated)
{
if (listTabLevelSecurity.Exists(x => x.usr_nm.ToString().ToLower() == UsrName.ToLower()))
{
TabLevelSecurityCurrentUser = listTabLevelSecurity.AsEnumerable().Where(x => (x.usr_nm.ToString().ToLower() == UsrName.ToLower())).Select(x => x).FirstOrDefault();
}
........
if (TabLevelSecurityCurrentUser != null)
{
switch (ActionTab)
{
//....
case "is_approver": strPermission = TabLevelSecurityCurrentUser.is_approver ?? "N";
strAddPermission = TabLevelSecurityCurrentUser.transaction_tb_access ?? "N";
break;
}
Based on this is_approver thing (it will be either set to 1 or 0)
I will either hide/show the 3 buttons "Approve","Reject","Research".
The template in angular is ...
<div class="home-grid-content" ng-controller="TransactionDetailsMergeController" style="width:100%;">
<div ng-style="pleaseWait">
<div class="refresh" style="width:100%;height:100px;">
<h4>Please wait....</h4>
</div>
</div>
<div class="row" ng-style="toggleMergeButtons">
<div class="col-lg-12">
<div style="padding-top:10px; padding-right:10px; float: left;">
<button type="button" class="btn btn-default" ng-model="ApproveRecords" ng-click="ApproveMerge(ApproveRecords)">Approve</button>
</div>
<div style="padding-top:10px; padding-right:10px; float: left;">
<button type="button" class="btn btn-default" ng-model="RejectRecords" ng-click="RejectMerge(RejectRecords)">Reject</button>
</div>
<div style="padding-top:10px;" padding-right:10px; float left;>
<button type="button" class="btn btn-default" ng-model="ResearchRecords" ng-click="Research(ResearchRecords)">Research</button>
</div>
</div>
</div>
<br />
<div ng-style="toggleDetails">
<div>
<h3>Merge Details</h3>
<div ui-grid="gridOptions" ui-grid-selection class="" ui-grid-pagination ui-grid-auto-resize>
<div class="watermark" ng-show="!gridOptions.data.length">No data available</div>
</div>
<div class="grid-pager">
<uib-pagination boundary-links="true" total-items="totalItems" items-per-page="4" ng-change="pageChanged(currentPage)" ng-show="(totalItems>4) == true"
ng-model="currentPage" class="pagination" direction-links="false" id="HconstUnmerge_1"
first-text="«" last-text="»">
</uib-pagination>
</div>
</div>
<br />
<div style="margin-top:8px;">
<button type="button" class="btn btn-default pull-left" ng-click="backToDetailsPage()">Cancel</button>
</div>
</div>
<div class="modal fade" id="accessDeniedModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Transaction Status</h3>
</div>
<br />
<br />
<div class="row" style="width:98%; ">
<div style="margin-left:40px;margin-right:40px;">
The Transaction will be posted to CDIM.
</div>
</div>
<br />
<div class="modal-footer">
<!--<button class="btn btn-default pull-left" ng-click="case.back()"> Back</button>-->
<div style="padding-top:10px;">
<button class="btn btn-default pull-right" type="button" ng-click="closeTransModal()">OK</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="accessDeniedRejectModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Transaction Status</h3>
</div>
<br />
<br />
<div class="row" style="width:98%; ">
<div style="margin-left:40px;margin-right:40px;">
The Transaction will not be posted to CDIM.
</div>
</div>
<br />
<div class="modal-footer">
<!--<button class="btn btn-default pull-left" ng-click="case.back()"> Back</button>-->
<div style="padding-top:10px;">
<button class="btn btn-default pull-right" type="button" ng-click="closeTransModal()">OK</button>
</div>
</div>
</div>
</div>
</div>
</div>
How can I do that "In Controller" ?
First, setup a global variable called SecurityVars that contains the rights of your users. You will need a Security class that determines the rights of your users.
<script type="text/javascript">
//rights contains an array of privileges a user can do, i.e. is_approver
var userRights = string.Join("','", Security.CurrentUserRights().Select(r => r.Flag).ToArray());
var SecurityVars = { Name: '#Html.Raw(Security.CurrentUser.Identity.Name)', Rights: ['#Html.Raw(userRights)'] }
</script>
Javascript
//setup a global security model
app.run(["$rootScope", function($rootScope){
$rootScope.security = new security();
}]);
var security = function() {
this.canApprove = checkApprover();
this.canReject = checkCanReject();
this.canResearch = checkCanResearch();
function checkApprover() { return SecurityVars.Rights.indexOf("is_approver") > -1 ? true : false; }
function checkApprover() { return SecurityVars.Rights.indexOf("is_rejector") > -1 ? true : false; }
function checkApprover() { return SecurityVars.Rights.indexOf("is_rejector") > -1 ? true : false; }
}
Then inside your controller, you can do this:
//attach the rootScope's security to local scope
$scope.security = $rootScope.security;
Finally, use security in your HTML.
HTML
<button id="approvePost" ng-disabled="!security.canApprove">Approve</button>

Touchstart works from second time on modal mobile

Hey guys i am having a very weird issue in my mobile application development through phonegap as i am trying to make a modal which contains some images and i am doing a touchstart event on each image in this modal which leads to changing their border color if any of the image is tapped(touchstarted) bas there is a very weird thing that happens the touchstart is fired only after the 2nd time i touch the image and then works totally fine its fired with every touch after this 2nd touch but the very first touch isnt recognized as a touch at all !! It's doesn't even go into the eventlistener of the touchstart as i tried it using alert and it didn't enter the function at all .. And for your information if such images are put outside the modal everything just works perfectly and the touchstart event occurs from the first touch so is this something has to do with modals or something !???! Cause i really don't know whats the problem and its driving me crazy !! .... I will post my code now for the javascript changing the border color of the images and the html page..
document.getElementById("back").addEventListener('touchstart',function(){
var x=document.getElementById("back");
if(x.style.borderColor=="rgb(50, 50, 50)")
{
x.style.borderColor=y;
}
else {
x.style.borderColor="#323232";
}
});
document.getElementById("shoulder").addEventListener('touchstart',function(){
var x=document.getElementById("shoulder");
if(x.style.borderColor=="rgb(50, 50, 50)")
{
x.style.borderColor=y;
}
else {
x.style.borderColor="#323232";
}
});
document.getElementById("chest").addEventListener('touchstart',function(){
var x=document.getElementById("chest");
if(x.style.borderColor=="rgb(50, 50, 50)")
{
x.style.borderColor=y;
}
else {
x.style.borderColor="#323232";
}
});
document.getElementById("legs").addEventListener('touchstart',function(){
var x=document.getElementById("legs");
if(x.style.borderColor=="rgb(50, 50, 50)")
{
x.style.borderColor=y;
}
else {
x.style.borderColor="#323232";
}
});
document.getElementById("biceps").addEventListener('touchstart',function(){
var x=document.getElementById("biceps");
if(x.style.borderColor=="rgb(50, 50, 50)")
{
x.style.borderColor=y;
}
else {
x.style.borderColor="#323232";
}
});
document.getElementById("triceps").addEventListener('touchstart',function(){
var x=document.getElementById("triceps");
if(x.style.borderColor=="rgb(50, 50, 50)")
{
x.style.borderColor=y;
}
else {
x.style.borderColor="#323232";
}
});
<button data-toggle="modal" data-target="#squarespaceModal" class="btn btn-primary center-block buttoncss">My Muscle!</button>
<div class="modal fade active" id="squarespaceModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-body">
<!-- Start Muscles Choices -->
<div class="top" style="background-color:#EEEEEE">
<ul>
<li>
<h4 style="color:#323232">What are you playing today ?</h4>
</li>
</ul>
<div>
<div class="container">
<div class="row">
<div class="col-xs-4">
<div>
<img id="back" class="img-circle" src='img/back.png' />
<h5 style="color:#323232" class="text-center" style="color:white">Back</h5>
</div>
</div>
<div class="col-xs-4">
<div>
<img id="shoulder" class="img-circle" src="img/Shoulder.png" />
<h5 style="color:#323232" class="text-center" style="color:white">Shoulders</h5>
</div>
</div>
<div class="col-xs-4">
<div>
<img id="chest" class="img-circle" src="img/BenchPress.png" />
<h5 style="color:#323232" class="text-center" style="color:white">Chest</h5>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="background-color:#EEEEEE" >
<div>
<div class="container">
<div class="row">
<div class="col-xs-4">
<div>
<img id="legs" class="img-circle" src='img/Legpress.png' />
<h5 style="color:#323232" class="text-center" style="color:white">Legs</h5>
</div>
</div>
<div class="col-xs-4">
<div>
<img id="biceps" class="img-circle" src="img/biceps.png" />
<h5 style="color:#323232" class="text-center" style="color:white">Biceps</h5>
</div>
</div>
<div class="col-xs-4">
<div>
<img id="triceps" class="img-circle" src="img/triceps.png" />
<h5 style="color:#323232" class="text-center" style="color:white">Triceps</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I don't know why, but if you remove the "fade" class from the modal, the touchstart event fires the first time.

jQuery - failed show/hide buttons

I was tried to add forms using jQuery and it succeeded.
This time I'm trying to show and hide some buttons(#remove_form, #add_form)
but always not working:(
my jQuery codes(referred this question's answer):
$(document).ready(function(){
var index_num = 1;
var max_num = 7;
$("#add_form").click(function(e){
e.preventDefault();
if(index_num < max_num){
index_num++;
$("#event").each(function(){
$(this).clone().insertAfter(this).attr("id","event" + index_num);
$("#add_form" + index_num).css("display","none");
$("#remove_form" + index_num).css("display","inline");
});
}
});
$("#remove_form" + index_num).click(function(e){
e.preventDefault(); $(this).parent(".row collapse").remove(); index_num--;
});
});
+) I did not wrote "#add_form" button's css code. just this:
#remove_form{
display: none;
}
HTML codes:
<div class="row collapse" id="event">
<div class="small-2 large-2 columns">
<h7>example</h7>
</div>
<div class="small-2 large-2 columns">
<form>example</form>
</div>
<div class="small-2 large-2 columns">
<form>example</form>
</div>
<div class="small-1 large-1 columns">
<h7>example</h7>
</div>
<div class="small-2 large-2 columns">
<form>example</form>
</div>
<div class="small-1 large-1 columns">
<h7>example</h7>
</div>
<div class="small-2 large-2 columns">
<button type="submit" class="button tiny alert" id="remove_form"></button>
</div>
<div class="small-2 large-2 columns">
<button type="submit" class="button tiny" id="add_form"></button>
</div>
</div>
+) HTML codes after clicking '#add_form' button:
<div class="row collapse" id="event">...</div>
<div class="row collapse" id="event7">...</div>
<div class="row collapse" id="event6">...</div>
<div class="row collapse" id="event5">...</div>
<div class="row collapse" id="event4">...</div>
<div class="row collapse" id="event3">...</div>
<div class="row collapse" id="event2">
...
<div class="small-2 large-2 columns">
<button type="submit" class="button tiny alert" id="remove_form"></button>
</div>
<div class="small-2 large-2 columns">
<button type="submit" class="button tiny" id="add_form"></button>
</div>
</div>
How can I solve this problem?
You have to use the id attribute only when you know your item is unique.
If you have multiple id="event" then you need to use class="event" instead and $(".event").each instead of $("#event").each.
If my assumptions are correct, you are trying to make a copy of event form when you click on #add_form button. Then, it's advised to provide a remove button inside the #event form so that every clone has his own remove button and a single add button outside of the #event element.
If you put it that way it's not about Show/Hide rather Add/Remove DOM elements.
<div id="to_clone" style="display:none">
<div class="row collapse" class="event">
...
<div class="small-2 large-2 columns">
<button type="submit" class="button tiny alert" class="remove_form"></button>
</div>
</div>
</div>
<div id="events_container">
<button type="submit" class="button tiny" id="add_form"></button>
</div>
Jquery
$('#add_form').click(function(){
event=$("#to_clone").html();
$(this).before(event);
});
$(document).on('click', '.remove_form', function(){
$(this).closest(".event").remove();
return false;
});
In case you're wondering how to submit those forms you can add a function that translate inputs into json.
function getEventsJson()
{
var json='[';
$('.event').each(function()
{
json=json+'{ "field1": "'+$(this).find('.field1class').val()+'","field2": "'+$(this).find('.field2class').val()+'"},';
});
json=json.replace(/,\s*$/, "");
json=json+']'
return json;
}
Or provide for each event it's own form and submit them one by one.
$('.event').each(function()
{
var form=$(this).find('form');
$.ajax({
type:"POST",
url: "/events",
data: {
'event' : form.serialize(),
},
dataType: 'json',
success: function(data) {
},
error: function(data){
}
});
}

Categories

Resources