Unable to delete form form inline formset in django - javascript

I have a inline formset called WorkExperienceFormset. I am generating form clicking a button. But I am unable to delete the forms. When I click button nothing is happening.
forms.py:
WorkExperienceFormset = inlineformset_factory(Employee, WorkExperience, extra=0, min_num=1,
fields = [
'previous_company_name',
'job_designation',
'from_date',
'to_date',
'job_description',
],
widgets = {
'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}),
'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}),
'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'),
'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'),
'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}),
},
can_delete = True,
can_order = True,
)
template.html:
<div class="work-formset">
{% for work_form in work_formset %}
<div class="work-form">
<div class="item form-group">
<label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Previous Company Name</label>
<div class="col-md-4 col-sm-4 col-xs-12">
<!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> -->
{{ work_form.previous_company_name }}
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Job Designation</label>
<div class="col-md-4 col-sm-4 col-xs-12">
<!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> -->
{{ work_form.job_designation }}
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Job Details</label>
<div class="col-md-4 col-sm-4 col-xs-12">
<!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> -->
{{ work_form.job_description }}
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">From Date</label>
<div class="col-md-2 col-sm-2 col-xs-12">
<!-- <input id="birthday" class="date-picker form-control col-md-7 col-xs-12" required="required" type="text"> -->
<div class="form-group has-feedback">
{{ work_form.from_date }}
<span class="fa fa-calendar-o form-control-feedback left m-1" aria-hidden="true"></span>
</div>
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">To Date</label>
<div class="col-md-2 col-sm-2 col-xs-12">
<!-- <input id="birthday" class="date-picker form-control col-md-7 col-xs-12" required="required" type="text"> -->
<div class="form-group has-feedback">
{{ work_form.to_date }}
<span class="fa fa-calendar-o form-control-feedback left m-1" aria-hidden="true"></span>
</div>
</div>
</div>
<div class="work-form-divider" id="">
</div>
</div>
{% endfor %}
</div>
script:
function cloneForm(selector, prefix) {
var newElement = $(selector).clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
var currentFormIndex = total;
newElement.find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});
total++;
$('#id_' + prefix + '-TOTAL_FORMS').val(total);
var solidLn = '<div class="ln_solid"></div>';
var deleteBtnId = prefix + '-' + currentFormIndex + '-btn';
deleteBtn = `<button type="button" value="remove" id="${deleteBtnId}" onClick="deleteForm('${deleteBtnId}', '${prefix}')"><i class="fa fa-minus" aria-hidden="true"></i></button>`
//deleteBtn = `<a type="button" value="remove" id=${deleteBtnId} onClick='deleteForm("delete", "prefix")'><i class="fa fa-minus" aria-hidden="true"></i></a>`
$(selector).after(newElement);
$(newElement).prepend(deleteBtn);
$(newElement).prepend(solidLn);
}
function deleteForm(btn, prefix) {
console.log(btn, prefix);
$(btn).parents('.work-form').remove('.work-form');
console.log("Button: " + $(btn).parents('.work-form'));
}
cloneForm() is working. But deleteForm() is not working. From the console.log I can see that deleteForm() is called when I press delete the button. Somehow .remove() is not working.
How can I solve this problem?

As it seems for this line $(btn).parents('.work-form').remove('.work-form');
.parents() -> The parents() method returns all ancestor elements of the selected element.
.remove() -> Remove the set of matched elements from the DOM.
Since remove() is the filter for the object in question, in this case, the object in question is just the single element with the id .work-form, therefore not containing any .work-form elements. Make sure to check your DOM and find that you have work-form elements present as a child.
You can simply solve this by using an unique identifier for the form in question instead of using the work-form
element.

Related

jQuery Cloning and incrementing input, textarea, that has name, id and for

I'm still very new to jQuery, and would need help to how to increment 3 elements in this code.
name, id & for.
The name consist of products[0]category, id consist of checkbox[0], for consist of checkbox[0] which is for labels on the checkbox that id use.
I've tried searching for examples. But all them haven't found any good results that i could learn from unfortunately. So in the codes below, they're not there to increase increment as i have totally no idea what else i can do to increase increment numbering.
$(document).ready(function() {
let $append = $('#append');
// append location's data listing
$append.on('change', '.location', function(){
var value = $(this).val();
$('.location_id').val($('#locations [value="'+value+'"]').data('locationid'));
$('.loc_desc').val($('#locations [value="'+value+'"]').data('locdesc'));
});
// enable checkbox for serialnumbers
$append.on('change','.enable-serial', function(){
let $item = $(this).closest('.product-item');
let $checkbox = $item.find('.enable');
$checkbox.prop('disabled', !this.checked);
});
// ctrl for key in checkbox
$append.on('click', '.keyin-ctrl', function() {
let $container = $(this).closest('.product-item');
let $serial = $container.find('.serial');
$container.find('.display').val(function(i, v) {
return v + $serial.val() + ';\n';
});
$serial.val('').focus();
});
// ctrl for del textarea
$append.on('click', '.undo-ctrl', function() {
let $container = $(this).closest('.product-item');
$container.find('.display').val('');
});
// clone product, increment products[x]var
$('#add_product').on('click', function() {
var itemNo = $('.product-item').length + 1;
var index = $('.product-item').length;
var regex = /^(.+?)(\d+)$/i;
let $product = $append.find('.product-item.template')
.clone()
.show()
.removeClass('template')
.insertAfter('.product-item:last');;
$product.find('span').text('#' + itemNo);
$product.find(':checkbox').prop('checked', false);
$product.find('.enable').prop('disabled', true);
$product.find('input, textarea').val('');
$('#append').append($product);
});
// delete product, but remain original template intact
$('#delete_product').on('click', function(){
var itemNo = $('.product-item').length + 1;
let $product = $append.find('.product-item:last:not(".template")');
$product.remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="shadow border">
<h4>{{ __('Product Details') }}</h4>
<hr>
<form method="post" action="">
<!-- Multiple Product addition -->
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Product Setting') }}</label><br/>
<div class="col-sm-5">
<button type="button" id="add_product" class="btn btn-dark">{{ __('Add Product') }} <i class="fas fa-plus-square"></i></button>
<button type="button" id="delete_product" class="btn btn-dark ml-3">{{ __('Delete Last Product') }} <i class="fas fa-minus-square"></i></button>
</div>
</div>
<hr>
<!-- Frist Group -->
<div class="product" id="append">
<!-- Product Details -->
<div class="product-item template">
<span>#1</span>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Category') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]category" type="text" placeholder="eg. 333" maxlength="3"required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Code') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]code" type="text" placeholder="eg. 22" maxlength="2" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Partnumber') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]partnumber" type="text" placeholder="eg. NGH92838" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Brand') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]brand" type="text" placeholder="eg. Rototype" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Quantities') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]qty" type="number" placeholder="eg. 1" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __("Location") }}</label>
<div class="col-sm-2">
<input class="form-control location" type="text" name="products[0]loc_name" list="locations" value="">
<input type="hidden" class="location_id" name="products[0]location_id" value="">
<input type="hidden" class="loc_desc" name="products[0]loc_desc" value="">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __("Description") }}</label>
<div class="col-sm-8">
<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Seial Number(s)') }}</label>
<div class="col-sm-5">
<input class="form-control enable serial" maxlength="25" placeholder="Key in Serial Number and hit button 'Key In'" disabled>
</div>
<div class="col-sm-5">
<button class="btn btn-dark enable keyin-ctrl" type="button" disabled>{{ __('Key In') }}</button>
<button class="btn btn-dark enable undo-ctrl" type="button" disabled>{{ __('Del') }}</button>
<input class="form-check-input ml-4 mt-2 pointer enable-serial" id="checkbox[0]" type="checkbox">
<label class="form-check-label ml-5 pointer" for="checkbox[0]">{{ __('tick to enable serialnumber')}}</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-5">
<textarea class="form-control display" name="products[0]serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>
</div>
</div>
<hr>
</div>
<!-- append start -->
</div>
<div class="form-group row">
<div class="col-sm-12 ">
#csrf
<button type="submit" class="btn btn-dark float-right ml-4">Next <i class="fas fa-caret-right"></i></button>
<!--<button type="button" class="btn btn-secondary float-right" onclick="history.back()">Previous</button>-->
</div>
</div>
<datalist id="locations">
#foreach($locations as $location)
<option value="{{ $location->loc_name}}" data-locationid="{{ $location->location_id }}" data-locdesc="{{ $location->loc_desc }}"></option>
#endforeach
</datalist>
</form>
</div>
</main>
So how do I actually achieve this to add increment to the NAME, ID and FOR my clones?
From the original template of products[0]variable to products[1]variable, checkbox[0] to checkbox[1]
If you want to increment either an ID, class, etc. you can't use .clone(), like the documentation warns:
Using .clone() has the side-effect of producing elements with
duplicate id attributes, which are supposed to be unique. Where
possible, it is recommended to avoid cloning elements with this
attribute or using class attributes as identifiers instead.
You'll have to do it "manually", following a very simple example below:
$( "#addrow" ).click(function() {
var count = $("#product").children().length;
$("#product").append("<input id='field[" + count + "]' type='text'>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="product">
</div>
<input id="addrow" type="button" value="Add field">

How to toggle a class of an input if it's not empty with jQuery?

Using Bootstrap 4.
I have four text inputs, if any of the text inputs contain any values, i'd like to add a class to a button.
When the button is clicked, I would like to clear the input values, and remove the class from the button.
I have half of it working (clicking button successfully clears all inputs).
My code is below;
$(document).ready(function() {
$("#filterRecords input").on("keyup change", function() {
$("#filterRecords input").each(function() {
var element = $(this);
if (element.val().length > 0) {
$('#resetFilter').addClass('btn-outline-primary');
}
});
});
$('#resetFilter').click(function() {
$('input[type=text]').val('').change();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row filterRecords">
<div class="input-group col-xs-6 col-sm-6 col-md-3 mb-3">
<input type="text" id="searchName" class="form-control" placeholder="Search Name">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="searchLang" class="form-control" placeholder="Search Language">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMin" class="form-control start" placeholder="Search Start Year">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMax" class="form-control end" placeholder="Search End Year">
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<button class="btn btn-sm btn-default" type="button" id="resetFilter">Reset Filters</button>
<hr>
</div>
</div>
Fiddle link.
Any help would be appreciated.
Firstly, filterRecords is a class, not an id, so your selector is incorrect.
Aside from that, the issue with your logic is that it only ever add the class when the input values change. You also need to have some logic to remove it when no input has a value entered.
You can do that by using toggleClass() along with a boolean based on the number of filled inputs, like this:
$(document).ready(function() {
var $inputs = $(".filterRecords input");
$inputs.on("input", function() {
var $filled = $inputs.filter(function() { return this.value.trim().length > 0; });
$('#resetFilter').toggleClass('btn-outline-primary', $filled.length > 0);
});
$('#resetFilter').click(function() {
$inputs.val('').trigger('input');
});
});
.btn-outline-primary {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row filterRecords">
<div class="input-group col-xs-6 col-sm-6 col-md-3 mb-3">
<input type="text" id="searchName" class="form-control" placeholder="Search Name">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="searchLang" class="form-control" placeholder="Search Language">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMin" class="form-control start" placeholder="Search Start Year">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMax" class="form-control end" placeholder="Search End Year">
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<button class="btn btn-sm btn-default" type="button" id="resetFilter">Reset Filters</button>
<hr>
</div>
</div>
Also note the use of input over the combination of keyup change.
Like this
$(document).ready(function() {
$("#filterRecords input").on("keyup change", function() {
$("#filterRecords input").each(function() {
var element = $(this);
if (element.val().length > 0) {
$('#resetFilter').addClass('btn-outline-primary');
}
});
});
$('#resetFilter').click(function() {
$("#filterRecords**")[0].reset();
$(this).removeClass('btn-outline-primary');
});
});

Remove a dynamic form field JS/HTML

I'm relatively new to JS and HTML and was following this tutorial ( https://www.youtube.com/watch?v=iaeCSh7YJDM&t=422s ) in order to turn a select box and input box into a dynamic form field in order to add as many of them as needed with an add button. The add button works perfectly, though after implementing the same code as in the video, the remove button does not function and I can't quite figure out why. I've gone back and rewatched and cross checked the videos code and mine though can't seem to see what I'm missing. Any help would be greatly appreciated. Below is the section of code I have.
HTML
<div class="form-group row" id = "addF" >
<label class="col-sm-3 col-lg-3 col-md-3 form-control-label">
Label
</label>
<div class="col-sm-4 col-lg-4 col-md-4">
<select class="form-control" id="xxxx" name="yyyyy" required>
<option class="placeholder" selected disabled value="" style="display:none;">Select Fact</option>
</select>
</div>
<div class="col-sm-3 col-lg-3 col-md-3">
<input type="text" class="form-control" id=vvvv" name="zzzz" required>
</div>
<div class="col-sm-1 col-lg-1 col-md-1">
<input type="button" id="add_fact()" onClick="addFact()" value="+">
</div>
</div>
JS
<script type="text/javascript">
var i =1;
function addFact(){
i++;
var div = document.createElement('div');
div.innerHTML = '<label class="col-sm-3 col-lg-3 col-md-3 form-control-label">Label '+i+'</label><div class="col-sm-4 col-lg-4 col-md-4"> <select class="form-control" id="xxxx'+i+'" name="yyyy_'+i+'" required><option class="placeholder" selected disabled value="" style="display:none;">Select Fact</option></select></div><div class="col-sm-3 col-lg-3 col-md-3"> <input type="text" class="form-control" id="vvvv" name="zzzz_'+i+'" required></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" id="add_fact()" onClick="addFact()" value="+"></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" value="-" onClick="removeFact(this)"></div>';
document.getElementById('addF').appendChild(div);
function removeFact(div) {
document.getElementById('addF').removeChild(div.parentNode);
i--;
}
</script>
In the "removeFact" function you are not receiving the div element; as you are calling it with "this" as parameter, you receive the button element, so to fix it, you must call the function like this
onClick="removeFact(this.parentNode)"
or change your function this way
function removeFact(button) {
document.getElementById('addF').removeChild(button.parentNode.parentNode);
i--;
}
You have to go one level deeper.
Try this :
<script type="text/javascript">
var i =1;
function addFact(){
i++;
var div = document.createElement('div');
div.innerHTML = '<label class="col-sm-3 col-lg-3 col-md-3 form-control-label">Label '+i+'</label><div class="col-sm-4 col-lg-4 col-md-4"> <select class="form-control" id="xxxx'+i+'" name="yyyy_'+i+'" required><option class="placeholder" selected disabled value="" style="display:none;">Select Fact</option></select></div><div class="col-sm-3 col-lg-3 col-md-3"> <input type="text" class="form-control" id="vvvv" name="zzzz_'+i+'" required></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" id="add_fact()" onClick="addFact()" value="+"></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" value="-" onClick="removeFact(this)"></div>';
document.getElementById('addF').appendChild(div);
}
function removeFact(div) {
document.getElementById('addF').removeChild(div.parentNode.parentNode);
i--;
}
</script>

how to add one or more clone in jquery

I am new in jquery and im using laravel framework. I want to add courses after filling first course by user.
When user click on add more course button.it will create new clone make sure that add more course button will be removed from first course and set to second course and same apply for newly created course and add more button should removed from second course and set to third course . i have hrml code.
enter code here
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="row">
<div class="heading">
<h4>Courses Offred <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="display:none">×</button></h4>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Title</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Fees</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Web Link</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Detail</span>
<textarea class="form-control txtfield m-tb-10 txtarea" rows="5" placeholder="Add Your Course Detail"></textarea>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Type</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Duration</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Location</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Entry Requirement</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Certificates</span>
<textarea class="form-control txtfield m-tb-10 txtarea" rows="5" placeholder="Add Your Certificates"></textarea>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="row">
<div class="add-more-class ">
<div class="btn-save">
<button class="btn btn-info">Add More Course</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
In heading tag there is close button.and it should visible in second course and make validation user can't add more than five course. Can anyone help me. Thanks in advance :)
I think this is the script that you wanted:
Updated script:
var courseCtr = 1;
console.log('course counter: ' + courseCtr);
$(document).on('click', 'button.btn', function() {
if (courseCtr === 5) {
return false;
}
var $row = $(this).closest('div.heading').parent();
var $parent = $row.parent();
var $clone = $row.clone();
if ($clone.find('.heading .close').length === 1) {
$clone.find('.heading .close').remove();
}
$clone.find('.heading h4').after('<button class="close">X</button>')
$clone.find(':input').val('');
$clone.find('textarea').val('');
$row.find('.heading div').last().remove();
// $clone.find('.heading h4').remove();
$parent.append($clone);
courseCtr++;
console.log('course counter: ' + courseCtr);
})
$(document).on('click', '.close', function(){
var $buttonClone = $(this).parent().find('div').last().clone();
$(this).parents('.row').prev().find('div.heading').append($buttonClone);
$(this).parents('.row').remove();
courseCtr--;
console.log('course counter: ' + courseCtr);
})
UPDATED FIDDLE: SEE FIDDLE HERE
I think you need to clean up your html markup a little bit and your work and code will be more easy and understable.
1-seperate Add More Course button from form-content.
2-give proper class to form container.
3-write a simple code and done.
Modified HTML CODE
<div class="col-md-12 col-sm-12 col-xs-12 forms-container">
<div class="row single-form">
<div class="heading">
<h4>Courses Offred</h4>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Title</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Fees</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Web Link</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Detail</span>
<textarea class="form-control txtfield m-tb-10 txtarea" rows="5" placeholder="Add Your Course Detail"></textarea>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Type</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Course Duration</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Location</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Entry Requirement</span>
<input type="text" class="form-control txtfield m-tb-10" placeholder="Enter value">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="property-type">
<span class="property-class">Certificates</span>
<textarea class="form-control txtfield m-tb-10 txtarea" rows="5" placeholder="Add Your Certificates"></textarea>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="alert alert-danger" style="display:none">
Please fill all the fields.
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="row">
<div class="add-more-class text-center ">
<button class="btn btn-info add-more-course">Add More Course</button>
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="row">
<div class="add-more-class ">
<button class="btn btn-info pull-right save-and-continue">Save and continue</button>
</div>
</div>
</div>
</div>
JAVASCRIPT CODE
var count = 0;
$('.add-more-course').click(function() {
if (count < 4) {
/* clone single .single-form container */
var $new_form = $(this).parents('.forms-container').find('.single-form').first().clone(true);
/* clear form data if any field is filled */
$new_form.find('input,textarea').val("");
/* remove heading text and enable close button */
$new_form
.find('.heading h4')
.text("")
.append('<button type="button" class="close">X</button>')
.end()
.find('.alert').css('display','none');
/* append it before add more course button */
$(this).parents('.forms-container').find('.single-form').last().after($new_form)
count++;
}
});
$('.forms-container').on('click', '.single-form .close', function() {
$(this).parents('.single-form').remove();
count--;
});
$('.forms-container').on('click', '.save-and-continue', function(){
var $form_container = $(this).parents('.forms-container'),
is_error = false;
$form_container.find('.single-form').each(function(ind, form){
var $form = $(form);
$form.find('input,textarea').each(function(ind,ele){
if($(ele).val() === "" || $(ele).val() === undefined){
$form.find('.alert').css('display','block');
is_error = true;
return false;
}
});
});
if(!is_error) {
// write ajax call or anything else what you want on success
}
});
I hope it will help you.
you can get help from below code,
jQuery(document).delegate('a.add-record', 'click', function(e) {
e.preventDefault();
var content = jQuery('#sample_table tr'),
size = jQuery('#tbl_posts >tbody >tr').length + 1,
element = null,
element = content.clone();
element.attr('id', 'rec-'+size);
element.find('.delete-record').attr('data-id', size);
element.appendTo('#tbl_posts_body');
element.find('.sn').html(size);
});
on click of add more button you need to create clone of first form of parent div and append with container.
Dynamically Add and Remove rows/html form in a Table Using jquery

clone jquery input file was not clearing

With my current code I am able to clone entire div. But if the user attach any documents then the user click add more button the data are remain same on the cloned div.
This is the code I have so far below that isn't working. You can also see this on js fiddle: Link
I have try with the following code `$(".custom-file-input").closest('form').trigger('reset'); But this was resetting the original div not the clone one. Some where I am lagging kindly please help me.
var count=0;
$(document).on("click", ".attch_add_button", function () {
var $clone = $('.cloned-row4:eq(0)').clone();
$clone.find('[id]').each(function(){this.id+=''});
$clone.find('.btn_more').after("<input type='button' class='btn_right btn_less1' id='buttonless'/>")
$clone.attr('id', "added"+(++count));
$clone.find('.preview').hide();
$clone.wrap('<form>');
$clone.closest('form').trigger('reset');
$clone.unwrap();
$(this).parents('.medica_rpt').after($clone);
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row4').length;
if(len>1){
$(this).closest(".btn_less1").parents('.medica_rpt').remove();
}
});
Here is the html code
<div class="medica_rpt cloned-row4" >
<div class="row">
<div class="col-xs-4 col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-xs-2 col-sm-1 col-md-2 col-lg-2 ctm_lft_mrpt">
<label class="lbl_accep">Accepted ?</label>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 ctm_lft_mrpt">
<label class="lbl_accep">Accepted by</label>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 ctm_lft_mrpt">
<label class="lbl_accep">Accepted on</label>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 ctm_lft_mrpt">
<label class="lbl_accepft">Document Remarks</label>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-sm-3 col-md-3 col-lg-3">
<div class="custom-file-input" id="custom-file-input">
<input type="file" class="check">
<input type="text" class="txt_field ctm_widt check" id="file_name" disabled placeholder="Attached File">
<button class="cst_select ">
<i class="fa fa-rotate-90">
</i> Attach
</button>
</div>
View
</div>
<div class="col-xs-2 col-sm-1 col-md-2 col-lg-2 ctm_lft_mrpt">
<input type="checkbox">
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 ctm_lft_mrpt">
<input type="text" class="smipt_Field" id="accpt_by" name="accpt_by" disabled/>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 ctm_lft_mrpt">
<input type="text" class="smipt_Field" id="accpt_on" name="accpt_on" disabled/>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 ctm_lft_mrpt">
<select class="slt_Field" id="txt_dcmRem" name="txt_dcmRem">
<option value="" selected='selected'> </option>
<option value="COLR">Coloured Copy Required</option>
<option value="EXPR">Expired Document</option>
<option value="INSF">Insufficient</option>
<option value="INVD">Invalid Document</option>
<option value="LOWR">Low Resolution</option>
</select>
</div>
</div>
<div class="row-fluid">
<div class="col-xs-12 col-sm-12 col-md-12 pull-right clear">
<input type="button" class="btn_more btn_right attch_add_button"/>
<!--<button class="btn_more btn_right attch_add_button"></button>-->
</div>
</div>
</div>
Thanks in advance
Kindly help suggest me I am confused here.
If you are cloning form elements best work around for this is to reset the cloned form.
In the fiddle example there is no form at all, so, in case you are cloning some input fields but not the whole form you might need to wrap those input inside a form, reset that form, and then unwrap.
Your JS should end up similar to this:
$(document).on("click", ".attch_add_button", function () {
var $clone = $('.cloned-row4:eq(0)').clone();
$clone.find('[id]').each(function(){this.id+=''});
$clone.find('.btn_more').after("<input type='button' class='btn_right btn_less1' id='buttonless'/>")
$clone.attr('id', "added"+(++count));
$clone.find('#custom-file-input').val('');
$clone.wrap('<form>');
$clone.closest('form').reset();
$clone.unwrap();
$(this).parents('.medica_rpt').after($clone);
});
You might want to check slipheed's answer on THIS question

Categories