jquery sortable not working on dynamically added items - javascript

I am trying to get .sortable from jQuery UI to work but it is only working for my first item, when I dynamically add new ones, it stops working.
I found this: http://api.jqueryui.com/sortable/#method-refresh which should refresh everything and recognize new items, but when I use that I get the error:
Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'refresh'
What can I do?
My code:
// HTML template for new fields
const template = `<div class="row sortwrap">
<div class="col-md-8">
<input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
<i class="mdi mdi-sort dragndrop"></i>
<div class="questionlist">
<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-success questionbutton">Extra vraag</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
const vraagTemplate = `<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
$('.sortwrap').sortable();
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
$('.sortwrap').sortable("refresh");
$('#dynamic_field input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
$('#dynamic_field .sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
$('#dynamic_field .questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append category template
$('#addcategory').click(function() {
$('#dynamic_field').append($(template));
updatePlaceholders();
});
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
$ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
If I remove the line that says refresh in my function and only have the one .sortable in my code then I can drag all items even new ones but nothing is dropping. So I can drag but not sort/drop.

I think this is on where you attach your sort. I used a wrapper here to do so.
Note I turned off the refresh due to where I attached it as it seems to not need that given that attachment point.
// HTML template for new fields
const template = '<div class="row sortwrap"> <div class="col-md-8"> <input type="text" name="category[]" placeholder="" class="form-control name_list catinput" /> <i class="mdi mdi-sort dragndrop"></i> <div class="questionlist"> <div class="row"> <div class="col-md-8"> <input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-success questionbutton">Extra vraag</button> </div> </div> </div> </div> <div class="col-md-4"> <button id="addcategory" class="btn btn-danger btn_remove">X</button> </div> </div>';
const vraagTemplate = '<div class="row"> <div class="col-md-8"> <input type="text" name="question[]" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-danger btn_remove">X</button> </div> </div>';
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
// $('#dynamic_field').sortable( "refresh" );
let df = $('#dynamic_field');
df.find('input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
df.find('.sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
df.find('.questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
let $ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(function() {
$('#addcategory').trigger('click');
$('#dynamic_field').sortable();
});
.sortwrap{border: solid green 1px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<button id="addcategory">add</button>
</div>
<div id="dynamic_field"></div>

As mentioned above this will work fine
This looks promising:
http://api.jqueryui.com/sortable/#method-refresh
it seems to imply that you can just add an item to a sortable, then call
$('#mysortable').sortable('refresh')
to recognize it.
var counter = 1;
function appendThing() {
$("<li id='Text" + counter + "' class='ui-state-default'>Text" + counter + "</li>").appendTo($("#mySortable"));
$("#mySortable").sortable({ refresh: mySortable })
counter++;
};
please take a look into this
https://jsfiddle.net/6ztrdg9n/

Related

Button click function not working in jQuery

So I'm developing a website for a medical clinic and they asked me to add a button beneath every doctor to make an appointment.
this is what i have for the doctors section
for (var i = 0; i < 3; i++) {
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].ficheiro + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" type="button" class="btn btn-primary">Marcar consulta</a>' +
'</div>' +
'</div>' +
'</div>'
);
}
The then code for the click function (that doesn't work):
$('#marcar').click(function() {
var offset = $('#marcacao').offset();
$('html, body').animate({
scrollTop: offset.top-100,
scrollLeft: offset.left
}, 1000);
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(medico[i].especialidade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(medico[i].nome);
console.log('test');
});
This is all inside a $(document).ready(function() {}); and what should do is when i click that button beneath the doctor, should go up to the form and fill the doctor's name and specialty... but it seems it's not working for some reason... this is a copy of other click functions in the code, but they seem to work fine.
HTML form:
<div id="marcacao-consulta" data-target="#marcacao-consulta">
<div class="row">
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="especialidade-marcacao" class="gui-input">
<option id="especialiade-default" value="default">Escolha a especialidade</option>
<?
$query = $dbHandle->prepare("
SELECT `especialidade`
FROM `especialidade`
ORDER BY `especialidade` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["especialidade"]; ?>"><?=$row["especialidade"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-heartbeat"></i></span>
</label>
</div>
</div>
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="corpo-clinico-marcacao" class="gui-input">
<option id="corpo-clinico-default" value="default">Escolha o médico</option>
<?
$query = $dbHandle->prepare("
SELECT `nome`
FROM `medico`
ORDER BY `nome` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["nome"]; ?>"><?=$row["nome"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-user-md"></i></span>
</label>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12">
<div class="section">
<label class="field prepend-icon">
<input id="nome" class="gui-input" type="text" placeholder="Nome Completo">
<span class="field-icon"><i class="fas fa-user"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="email" class="gui-input" type="text" placeholder="Endereço de correio eletrónico">
<span class="field-icon"><i class="fas fa-envelope"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="telefone" class="gui-input" type="text" placeholder="Telefone/Télemovel">
<span class="field-icon"><i class="fas fa-phone-square"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="tipo" class="gui-input" type="text" value="consulta" disabled>
</label>
</div>
</div>
</div>
</div>
You have to add the element and register the event for the element. Here is the fiddle which works for you
https://jsfiddle.net/0q3kpyfv/
Your sample HTML
<div id="get_medicos">
</div>
Sample jquery code
Notice I have added the data-val attribute to the added anchor tag which will help you to get the information and perform the logic based on which button is clicked. you can pass dynamic data to data-val attribute and use it in click event.
$(document).ready(function() {
var sampleString = "";
var medico = [{'especialidade':'speciality 0','nome':'Doctor 0'},{'especialidade':'speciality 1','nome':'Doctor 1'},{'especialidade':'speciality 2','nome':'Doctor 2'}]
for (var i = 0; i < 3; i++) {
var doctorData = medico[i];
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].especialidade + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" data-doctor-especialiadade="'+medico[i].especialidade+'" data-doctor-nome="'+medico[i].nome+'" type="button" class="btn btn-primary">Marcar consulta'+i+'</a>' +
'</div>' +
'</div>' +
'</div>'
);
};
$('#get_medicos').on('click','a',function(event){
var elementClicked = event.target;
var doctorEspecialiadade = $(elementClicked).data('doctor-especialiadade');
var doctorName = $(elementClicked).data('doctor-nome');
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(doctorEspecialiadade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(doctorName);
})
});
if you create the button after your event, you could have problem so, use the delegate version of click:
$('div').on('click', 'a', (function()....
and better put an id on the ancestor div:
'<div class="text-box white padding-3" id="mydiv"'
:
$('#mydiv').on('click', 'a', (function()....
another thing, with the loop you will have same id more time in your html??its no good.
so you'll have to rebuild your program logic...and bind the event with the right button (use a common class) it will be better than an id
If you bind the event to the parent element, and filter by the children, you can listen to any new elements that are added, doesn't matter how many.
<div class="container"></div>
<button class="js-add-new">Add new</button>
const $addNew = $('.js-add-new')
const $container = $('.container')
let count = 0
$addNew.on("click", () => {
count += 1
$container.append(`
<div>
<button>log me ${count}</button>
</div>
`)
})
$container.on("click", "button", (event) => {
console.log(event.currentTarget)
})
A working example: https://codepen.io/alexmccabe/pen/jOrXZxj?editors=1111
The button click is working. Here is a fiddle showing it does:
https://jsfiddle.net/bradberkobien/qL4m10y6/3/
There must be an issue with the code that comes before the console.log("test") line within the click. I would use the debugger to help you with that.

Manipulating element by ID

I'm creating a plugin for Input Files, I created everything but without having in mind the possibility of having multiple inputs on screen, then it was necessary instead to manipulate the element from the element ID. This is so that actions in one input do not affect all other inputs on the screen.
Below is the code so far, I could not make it work when informed by the element ID.
function bs_input_file() {
// TODO: add function to hide remove button when file not informed
const inputElement = $(".input-file").find('input');
const inputId = inputElement.map(function (index, dom) {
return dom.id
});
buttonInspec(inputId);
function buttonInspec(id) {
$("#" + id).find("button.btn-reset").addClass("hidden");
var element = $("#" + id).find('input');
element.on("change input propertychange", function() {
console.log("changed!")
if (element.val() != "") {
$("#" + id).find("button.btn-reset").removeClass("hidden");
}
});
}
// Necessary to put ID below also
$(".input-file").before(
function() {
if (!$(this).prev().hasClass('input-ghost')) {
var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
element.attr("name", $(this).attr("name"));
element.change(function() {
element.next(element).find('input').val((element.val()).split('\\').pop());
});
$(this).find("button.btn-choose").click(function() {
element.click();
});
$(this).find("button.btn-reset").click(function() {
element.val(null);
$(this).parents(".input-file").find('input').val('');
});
$(this).find('input').css("cursor", "pointer");
$(this).find('input').mousedown(function() {
$(this).parents('.input-file').prev().click();
return false;
});
return element;
}
}
);
}
bs_input_file();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h3>Example</h3>
<form method="POST" action="#" enctype="multipart/form-data">
<!-- COMPONENT START -->
<div class="form-group">
<div class="input-group input-file" name="Fichier1">
<input id="fileInput0" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group input-file" name="Fichier2">
<input id="fileInput1" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<!-- COMPONENT END -->
</form>
</div>
</div>

Form in ajax post method sends empty object

I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.

Save multiple dynamically added file in mongoose

I'm using Ajax to add (and remove) multiple fields in a form, and then submitting them to mongoose to save them. Unfortunatelly I'm able to retrieve and save only 1 array, missing completely the dinamically added ones.
HTML: Here's a form with a form-group visible, where I inizialise the array using name attributes,and a form-group template that I dinamically populate with Ajax
<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}">
<section class="panel">
<div class="panel-body">
<div class="form-group" data-option-index="1">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="options[0][optionType]">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionValue]">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionPrice]">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="form-group hide" id="optionTemplate">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="optionType">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionValue">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionPrice">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<footer class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</footer>
</section>
</form>
AJAX: I use this to add rows or remove them, each with 3 inputs. Before submitting the form I use .serialize() to get the arrays by their names
$(document).ready(function() {
var optionIndex = $(".form-group[data-option-index]").length;
$('#productAdd').submit(function(e) { // add product submit function
e.preventDefault();
$(this).ajaxSubmit({
contentType: 'application/json',
data: $('form[name="productAdd"]').serialize(),
error: function(xhr) {
console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText);
},
success: function(response) {
if (typeof response.redirect === 'string')
window.location = response.redirect;
}
});
return false;
})
// Add button click handler
.on('click', '.addButton', function() {
optionIndex++;
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-option-index', optionIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
.find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end()
.find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end();
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-option-index');
// Remove fields
$row.find('[name="options[' + index + '].title"]').remove();
$row.find('[name="options[' + index + '].isbn"]').remove();
$row.find('[name="options[' + index + '].price"]').remove();
// Remove element containing the fields
$row.remove();
});
});
NODEJS: Here's my nodejs route, I use multer for managing file upload. I've a foreach should manage the inputs from the form, but it just see the first element.
router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) {
var newProduct = new Product();
newProduct.imagePath = req.file.filename;
newProduct.title = req.body.title;
newProduct.description = req.body.description;
newProduct.price = req.body.price;
newProduct.save()
.then(function (product) {
console.log(req.body.options);
req.body.options.forEach(function (option) {
var newOption = new ProductOption();
newOption.type = option.optionType;
newOption.value = option.optionValue;
newOption.price = option.optionPrice;
newOption.product = product;
newOption.save();
});
})
.then(function (options) {
req.flash('success', 'Product uploaded correctly.');
res.send({redirect: '/user/shop/products/add'});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to save the newAddress to DB: ' + err);
});
});
It was a simple mistake, I named the fields dinamically added, differently from the static ones.
this code
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
should be like this
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end()

How to dynamically Add/Remove file type input field using jquery?

I cannot remove input field dynamically, I can add field but my remove option is not working.
I am using jquery for dynamically add/remove field and bootstrap 3 for my layout.
Here is my markup:
<div class="row margin-bottom">
<div class="col-md-12 col-sm-12">
<button type="submit" class="add-box btn btn-info"><span class="glyphicon glyphicon-plus"></span> Add More Fields</button>
</div>
</div>
<?php $attributes = array('class' => 'form-horizontal', 'role' => 'form'); echo form_open_multipart('config/upload_image', $attributes);?>
<div class="text-box form-group">
<div class="col-sm-4"><input type="file" class="" name="txtImage[]" id="imageinput"/></div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-upload"></span> Upload</button>
</div>
</div>
<?php echo form_close();?>
Here is my jquery code:
$(document).ready(function(){
$('.add-box').click(function(){
var n = $('.text-box').length + 1;
if(n > 5)
{
alert('Only 5 Savy :D');
return false;
}
var box_html = $('<div class="text-box form-group"><div class="col-sm-4"><input type="file" class="" name="txtImage[]" id="imageinput'+ n +'"/></div><div class="col-sm-2"><button type="submit" class="remove-box btn btn-danger btn-sm"><i class="fa fa-minus-circle fa-lg"></i></button></div></div>');
$('.text-box:last').after(box_html);
box_html.slidedown('slow');
});
$('.form-horizontal').on('click', '.remove-box', function(){
$(this).parent().remove();
return false;
});
});
The error is in the remove button click event handler. You need to remove the closest form group rather than the immediate parent:
$('.form-horizontal').on('click', '.remove-box', function(){
$(this).closest(".form-group").remove();
return false;
});
check this bootply for a working example: http://www.bootply.com/x8n3dQ6wDf
EDIT
for animation on remove you can use jQuery slideUp like this:
$('.form-horizontal').on('click', '.remove-box', function(){
var formGroup = $(this).closest(".form-group");
formGroup.slideUp(200, function() {
formGroup.remove();
});
return false;
});

Categories

Resources