how to add one or more clone in jquery - javascript

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

Related

How to have no validation when selecting a value on dropdown

On this form to create a link when I select another committee type the form validates for all of the blank fields that are required. I am trying to figure out a way so those fields don't validate when I select another committee type in the dropdown. Currently when I debug it doesn't get to the post action method in the controller for obvious reasons that the form validates before even getting into the controller.
If you need to see more code like the action method in controller or view model I can provide that as well.
View
<div class="form-group col-md-8">
<div asp-validation-summary="All" id="validation-error" class="text-danger custom-validation-
summary"></div>
</div>
<input id="link-id" asp-for="#Model.LinkId" type="hidden" />
<input name="FetchCategories" type="hidden"/>
<div class="form-group col-md-8 col-lg-4">
<div class="form-group">
#{
var authorizedCommitteeTypes = await Model.CommitteeType
.ToSelectListAsync(AuthorizationService, User, AuthRequirements.AdminCommitteeType);
if (authorizedCommitteeTypes.Count == 1)
{
<input id="committeeType" name="committeeType" type="hidden"
value="#authorizedCommitteeTypes.FirstOrDefault()?.Value" />
}
else
{
<label class="control-label">Committee Type</label>
<select id="add-edit-committee-type"
name="committeeType"
asp-for="#Model.CommitteeType"
asp-items="#authorizedCommitteeTypes"
class="form-control">
</select>
}
}
</div>
</div>
<div class="form-group col-md-8 col-lg-4">
<label class="control-label">Category</label>
#{
if (Model != null && Model.AvailableCategories != null)
{
var availableCategories =
new SelectList(
Model.AvailableCategories.OrderBy(c => c.Order),
dataValueField: "CategoryId",
dataTextField: "Title",
selectedValue: Model.CategoryId);
<select id="dropdown-linkCategories" required
asp-for="#Model.CategoryId"
asp-items="#availableCategories"
class="form-control">
<option>-- Select --</option>
</select>
}
else
{
<select id="dropdown-linkCategories"
class="form-control">
<option>-- Select --</option>
</select>
}
}
</div>
<div class="form-group col-md-8 col-lg-4">
<label class="control-label">Title</label>
<input id="title" asp-for="Title" name="Title" class="form-control" />
</div>
<div class="form-group col-md-8 col-lg-4">
<label class="control-label">Display Order</label>
<div>
<input id="order" asp-for="Order" name="Order" class="form-control" />
</div>
</div>
<div class="form-group col-md-8 col-lg-4">
<label class="control-label">URL</label>
<input id="url" asp-for="URL" name="URL" class="form-control" />
</div>
<div class="form-group col-md-8 col-lg-12">
<label class="control-label">Description</label>
<textarea class="rtextDescription" name="Description" id="Description" row="1" cols="60"
data-val-maxlength-max="200" asp-for="Description"
data-val-maxlength="Max length for Description is 200"></textarea>
</div>
#{
if (Model.LinkId == 0)
{
<div class="form-group col-md-12">
<input type="submit" id="link-submit"
class="btn btn-forum col-sm-12 col-md-2 col-lg-2"
value="Add" />
<a asp-area="Admin"
asp-controller="Link"
asp-action="Index"
class="btn btn-forum col-sm-12 col-md-2 col-lg-2">Back to Links</a>
</div>
}
else
{
<div class="form-group col-md-8 col-lg-12">
<input type="submit" value="Save" id="edit-submit"
class="btn btn-forum col-sm-12 col-md-2 col-lg-2" />
<a asp-area="Admin"
asp-controller="Link"
asp-action="Index"
class="btn btn-forum col-sm-12 col-md-2 col-lg-2">Back to Links</a>
</div>
}
}
JS
$(document).on("change", "#form-create-link #add-edit-committee-type", function () {
$('input[name="FetchCategories"]').val(true);
$(this).closest('form').submit()
});

Unable to delete form form inline formset in django

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.

How to delete div and all element inside div? Javascript, html, css

I have a function that clears the entire div and it disappears but still appears in the inspect (html). This is a real problem because we have this input type field on the email and I got this empty data in email. I only want when this value is not chosen to completely remove me from html and inspect. Look at my code and try to catch the error. The most important things in the whole code that you need to pay attention are onchange="checkSelected()" in html and first script tag which manipulate with that. It should simply become a display none but it still stands there.
<div class="modal fade" id="montageModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content" style="display: flex;">
<div class="modal-body">
<form id="schedule_form" class="clearfix" action="index.php?route=api/reifenmontage" method="post">
<div class="container-fluid">
<div class="step_1" >
<h3 class="modal-title">Reifenmontage Termin buchen </h3>
<div class="row termin_row">
<div class="col-xs-12 col-sm-4">
<div class="row">
<label>Pneu-Typ</label>
</div>
</div>
<div class="col-xs-12 col-sm-6">
<div class="row">
<select onchange="checkSelected()" class="form-control" name="pneu" id="pneu">
<option value="Motorrad">Motorrad</option>
<option value="Auto">Auto</option>
</select>
</div>
</div>
</div>
<div id="additionalRow" class="row termin_row" >
<div id="reifenmontage-input" class="row termin_row">
<div class="col-xs-12 col-sm-4">
<div class="row">
<label>Mark und model</label>
</div>
</div>
<div class="col-xs-12 col-sm-4">
<div class="row">
<select name="marka" class="form-control" id="button-getdata">
</select>
</div>
</div>
<div class="col-xs-12 col-sm-4">
<div class="row">
<select name="model" class="form-control" id="result" >
</select>
</div>
</div>
</div>
</div>
<div class="row termin_row">
<div class="col-sm-4 col-xs-12">
<div class="row"><label>2. Terminvorschlag</label></div>
</div>
<div class="col-sm-4 col-xs-6">
<div class="row">
<div class="input-group date" id="date-2" data-termin="1">
<input type='text' class="form-control" name="date[1]" />
<span class="input-group-addon">um</span>
</div>
</div>
</div>
<div class="col-sm-4 col-xs-6">
<div class="row">
<div class="input-group time" id="time-2" data-termin="1">
<input type='text' class="form-control" name="time[1]" />
<span class="input-group-addon">Uhr</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="checkbox">
<label>
<input type="checkbox" name="accept" id="accept"> Ich akzeptiere die Teilnahmebedingungen
</label>
</div>
</div>
<div class="row text-center">
<button type="button" class="btn btn-primary btn-lg btn-submit" id="next_step" disabled="disabled">Anfrage senden</button>
</div>
</div>
<div class="step_2">
<h3 class="modal-title">Your contact info</h3>
<div class="">
<div class="form-group clearfix">
<input type="text" name="name" value="<?= $user['name'] ?>" placeholder="Name and Lastname" class="form-control name text" required />
</div>
<div class="form-group clearfix">
<input type="text" name="phone" value="<?= $user['phone'] ?>" placeholder="Phone" class="form-control phone text" required />
</div>
<div class="form-group clearfix">
<input type="email" name="email" value="<?= $user['email'] ?>" placeholder="Email" class="form-control email text" required />
</div>
<div class="text-center">
<button type="submit" id="submit" class="btn btn-default btn-lg btn-submit" >Suchen</button>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">SCHLIESSEN</button>
</div>
</div>
</div>
</div>
and my script tag
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
let additionalRow = document.getElementById('additionalRow');
function checkSelected() {
if (selectItem.selectedIndex == "1") {
additionalRow.style.display = 'none';
} else {
additionalRow.style.display = 'block';
}
}
</script>
<script type="text/javascript">
$('#button-getdata').on('change', function() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
},
success: function(json) {
if (json['success']) {
$("#result").empty();
for (i in json['success']) {
var element = json['success'][i];
var o = new Option(element['model'], element['model']);
$("#result").append(o);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$("#result").append(o);
}
// document.getElementById("schedule_form").reset();
}
}
});
});
</script>
<script type="text/javascript">
$.ajax({
url: 'index.php?route=api/reifenmontage/mark',
context: document.body,
success: function(data) {
const selectControl = $('#button-getdata');
selectControl.html(data.map(ExtractData).join(''));
}
});
function ExtractData(item) {
return ` <option value="${item.value}">${item.label}</option>`;
}
</script>
Try variant with detaching/attaching DOM elements
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
//let additionalRow = document.getElementById('additionalRow');
let detached = '';
function checkSelected() {
if (selectItem.selectedIndex == "1") {
detached = $('#reifenmontage-input').detach();
} else {
detached.appendTo('#additionalRow');
}
}
</script>

Data Form reset is not happening

Written code to save the data and reset the data. In this case data is saving successfully but unable to make reset the form. When i click on pencil icon it turn to floppy disk and remove icon. If i click on floppy disk data is saving but when i click on remove icon data form is not being reset. I tried code this way
//Banking details form validation
$(document).ready(function() {
$('.editBankDetailBtn').click(function() {
if ($('.editBankDetail').is('[readonly]')) { //checks if it is already on readonly mode
$('.editBankDetail').prop('readonly', false); //turns the readonly off
$('.editBankDetailBtn').html(
'<span class="glyphicon glyphicon-floppy-disk"> </span>' +
'<span id="reset-form" class="glyphicon glyphicon-remove"> </span>');
// $('.glyphicon-remove')[0].reset();
} else { //else we do other things
var patt = /^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/;
var reg = /^[A-Za-z]{4}[0-9]{6,7}$/;
patt.test('acdbdfdsfsf22-333-666666'); // true
var bname_1 = document.getElementById('name').value;
if (bname_1 == "") {
document.getElementById('name').style.borderColor = "red";
return false;
} else {
document.getElementById('name').style.borderColor = "#cccccc";
}
$('.editBankDetail').prop('readonly', true);
$('.editBankDetailBtn').html(
'<span class="glyphicon glyphicon-pencil"> </span>');
$('.glyphicon-remove').on('click', function() {
$("#reset-form").trigger("reset");
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading" style="background-color: #b3daff;">
<h4 class="panel-title">
<span style="font-weight: 700;">Banking Details</span> <a class="editBankDetailBtn"><span
class="glyphicon glyphicon-pencil"> </span></a>
<a data-toggle="collapse" data-parent="#accordion" href="#collapseFour"> <span class="glyphicon glyphicon-plus" id="pls" style="color: darkred"> </span>
</a>
</h4>
</div>
<div id="collapseFour" class="panel-collapse collapse">
<div class="panel-body">
<div class="col-sm-4 col-md-6">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">Bank
Name<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<input type="text" class="form-control editBankDetail" id="bankName" readonly placeholder="Bank Name" />
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-6">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">Account
Number<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<input type="text" class="form-control editBankDetail" id="accountNumber" readonly placeholder="Account Number" />
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-6">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">IFSC
CODE<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<input type="text" class="form-control editBankDetail" id="ifscCode" readonly placeholder="IFSC CODE" />
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-12">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">Bank
Address<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<textarea class="form-control editBankDetail" id="branchAddress" placeholder="Bank Address" readonly> </textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!----Ends second column-------->
</div>
</div>
<!----Ends accordion column-------->
</div>
You have several things
You need to reset a form, not an icon like you do now
PLEASE have a toggleClass on the bankName - it is not name, but bankName in your code
You need to delegate - something like this - the element that gets the event handler has to be static in the page and exist at the time of delegation, here $('.editBankDetailBtn')
$('.editBankDetailBtn').on('click', '.glyphicon-remove', function() {
$("#myForm")[0].reset()
});
Your click will not work on the ones created dynamically. Add below code
$(document).on('click', '.glyphicon-remove', function() {
// Put one alert or console to check that you here
$("#YOU_FORM_ID")[0].reset(); //
});

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');
});
});

Categories