My actual html code:
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="<?php echo $adminData->name; ?>">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="<?php echo $adminData->email; ?>">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
I have multiple such panels, each one with a button that has specific ID. My goal is to collect all the input within the panel that the button was pressed. Although this sounds easy, my MAIN goal is to reuse the same function on multiple pages that have multiple panels (since the structures is simillar), to then use ajax to update the information. The only thing that I would need to provide the function is the id of the button so it can find automatically the relative input.
I am trying to accomplish this in vanilla js, though im ok with jquery.
My actual js code:
document.getElementById('savePersInfo').onclick = function(){
var inputArray = ['adminName', 'adminEmail'];
console.log(collectInfo(inputArray));
};
function collectInfo(inputArray){
$inputValueArray = []
for(var c = 0; c < inputArray.length; c++){
$inputValueArray[c] = document.querySelectorAll('[name="' + inputArray[c] + '"]')[0].value;
}
return $inputValueArray;
}
As you see here I need to specify the name of the input to be able to retrieve it, what I want is not to do that and have JS find it automatically based on the panel is was clicked on.
Any suggestions/ideas on how this can be accomplished ?
ps: ignore the inline styling and other layout stuff, early development phase.
You can use either javasscript's closest() or jQuery's closest(), and with those find the closest element being ancestor to both the button and input's, e.g. panel-body.
From there you then simply use that element as starting point, e.g. with javascript element.querySelectorAll), and select all inputs and grab their value.
Note, if to use the javascript version and support IE (it doesn't know of closest()), you can make use of the "polyfill" I added at the end.
Updated based on a comment, where I added a checkbox and select to my "javascript" code sample to show it works with those too, and how to get the button id.
Stack snippet - javascript
document.querySelectorAll('button').forEach( function(btn) {
btn.addEventListener('click', findInputs);
})
function findInputs() {
console.clear();
var button_id = this.id;
this.closest('.panel-body').querySelectorAll('input, select').forEach( function(inp) {
var test_checked = ((inp.type == 'checkbox' && inp.checked) ? ' checked' : '');
console.log(button_id, inp.value + test_checked)
})
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test</span>
<input type="checkbox" name="adminTest" class="form-control" value="test 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test 2</span>
<select name="adminTest2" class="form-control">
<option value="Test2-a">Test2-a</option>
<option selected value="Test2-b">Test2-b</option>
<option value="Test2-c">Test2-c</option>
</select>
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
Stack snippet - jQuery
$('button').each( function() {
$(this).click(findInputs);
})
function findInputs() {
$(this).closest('.panel-body').find('input').each( function() {
console.log( $(this).val() );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal 2
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 2">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 2">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo2">Guardar Alteração 2</button>
</div>
</div>
</div>
Add javascript closest() support for IE9+
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
if (!Element.prototype.closest)
Element.prototype.closest = function(s) {
var el = this;
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
Src: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
You can use Element.closest() on the element with the passed id to target the panel you are looking for. Then use Array.prototype.map() to return the value of all inputs from the selected panel.
Try the following way:
document.getElementById('savePersInfo').onclick = function(){
console.log(collectInfo(this.id));
};
function collectInfo(id){
var panel = document.getElementById(id).closest(".panel.panel-primary")
var $inputValueArray = [...panel.querySelectorAll('input[type=text]')].map(i => i.value);
return $inputValueArray;
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="John Michale Kane">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="john#gmail.com">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
Related
I have been trying to troubleshoot this error with the form submission. I am using the Livevalidation library in order to validate the email address field. Something isn't connecting properly to the library as I get this error in dev tools console. The library isnt getting called in under to validate the form field. Any help would be greatly appreciated.
ERROR:
Uncaught TypeError: Cannot read property 'form' of null
at LiveValidation.initialize (livevalidation_standalone.compressed.js:5)
at new LiveValidation (livevalidation_standalone.compressed.js:5)
at <anonymous>:2:13
at api.min.js:2
at Module.S (api.min.js:2)
at t.inlineScripts (api.min.js:2)
at api.min.js:2
HTML:
<form method="post" name="Camp-2021-05-Aware-ParkNeedsUs-FRM-Lightbox" action="https://s989596683.t.eloqua.com/e/f2" onsubmit="return handleFormSubmit(this)" id="form210" class="elq-form">
<input value="Camp-2021-05-Aware-ParkNeedsUs-FRM-Lightbox" type="hidden" name="elqFormName" />
<input value="989596683" type="hidden" name="elqSiteId" />
<input name="elqCampaignId" type="hidden" />
<div class="layout container-fluid">
<div class="row">
<div class="grid-layout-col">
<div class="layout-col col-sm-12 col-xs-12">
<div id="formElement0" class="elq-field-style form-element-layout row">
<!--div style="text-align:left;" class="col-sm-12 col-xs-12">
<label class="elq-label " for="fe2045">Email Address
</label>
</div-->
<div class="col-sm-12 col-xs-12">
<div class="row">
<div class="col-xs-12">
<div class="field-control-wrapper" style="width: 65%; margin-left: auto; margin-right: auto;">
<input
type="text"
class="elq-item-input"
name="emailAddress"
id="f20"
style="width: 100%; font-size: 14px; color: #828282;"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value="Email Address"
maxlength="50"
/>
<script type="text/javascript">
var f20 = window.document.getElementById("f20");
</script>
<script type="text/javascript">
var f20 = new LiveValidation("email");
f20.add(Validate.Email);
</script>
<script type="text/javascript">
var title = new LiveValidation("title", { onlyOnSubmit: true });
title.add(Validate.Email);
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="grid-layout-col">
<div class="layout-col col-sm-12 col-xs-12">
<div id="formElement1" class="elq-field-style form-element-layout row">
<div class="col-sm-12 col-xs-12">
<div class="row">
<div class="col-xs-12">
<div align="center">
<input type="Submit" class="submit-button-style" value="Submit" id="fe2046" style="margin-top: 8px; background-color: #286140; padding: 12px; border: none; width: 65%; color: white;" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="https://img04.en25.com/i/livevalidation_standalone.compressed.js"></script>
I have an array of text fields (user interface) that created HTML, CSS, Javascript using inside of the user interfaces.
The problem is when input elements that don't print or send the whole array. I want to print the whole array. It prints one array element.
order.php (user interface):
<div class="row">
<form id="ex_order" action="includes/exchange-order.inc.php" method="POST">
<div id="main_div" class="main_sec_div">
<div class="col-lg-12 col-ml-12">
<button type="button" id="add" class="btn btn-primary"><i class="fas fa-plus"></i></button>
</div>
<div class="col-lg-12 col-ml-12 group">
<div class="row" style="padding:0rem 1rem 1rem 1rem; padding-bottom:1.5rem; margin:2rem 0.2rem 2rem 0.2rem; background:#ccc;">
<div class="col-12 mt-5" style="margin:-1rem;">
<span style="margin-left:1rem;" class="status-p bg-primary">Passanger #1</span>
</div>
<!-- Add Ticket Information start -->
<div class="col-3 mt-5">
<div class="card">
<div class="card-body">
<h4 class="header-title">Ticket Infromation</h4>
<p class="text-muted font-14 mb-4">Here are want to add <code>Ticket Infromation</code> of Exchange Order.</p>
<div class="form-group">
<label for="example-text-input" class="col-form-label">Passenger Name</label>
<input name="p_name[]" class="form-control" type="text" id="p_name" required>
</div>
<div class="form-group">
<label for="validationCustom03">Ticket No.</label>
<input name="ticket_no[]" type="text" class="form-control" id="ticket_no" required>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="submitOrder" id="submitOrder" class="btn btn-primary mt-4 pr-4 pl-4">Save</button>
<!-- Jquery -->
<script>
$(document).ready(function() {
let i = 0;
let passCount = 1;
console.log('Default i : ', i);
// add button
$(document).on('click', '#add', function() {
i++;
console.log('Add', i);
html = `
<div class="col-lg-12 col-ml-12 second-div" id="sec_div${i}">
<div class="row" style="padding:0rem 1rem 1rem 1rem; padding-bottom:1.5rem; margin:2rem 0.2rem 2rem 0.2rem; background:#ccc;">
<div class="col-12 mt-5" style="margin:-1rem; display:flex; height:60px; align-items:center; align-content:center; justify-content:space-between;">
<div>
<span style="margin-left:1rem;" class="status-p bg-primary">Passanger #${++passCount}</span>
</div>
<div>
<button style="margin:1rem 1rem 0 0;" type="button" name="remove" id="${i}" class="btn btn-danger btn-sm remove"><i class="fa fa-close"></i></button>
</div>
</div>
<div class="col-3 mt-5">
<div class="card">
<div class="card-body">
<h4 class="header-title">Ticket Infromation</h4>
<p class="text-muted font-14 mb-4">Here are want to add <code>Ticket Infromation</code> of Exchange Order.</p>
<div class="col-md-12 mb-3">
<label for="example-text-input" class="col-form-label">Passenger Name</label>
<input name="p_name[]" class="form-control" type="text" id="p_name" required>
</div>
<div class="col-md-12 mb-3">
<label for="validationCustom03">Ticket No.</label>
<input name="ticket_no[]" type="text" class="form-control" id="ticket_no" required>
</div>
</div>
</div>
</div>
</div>
</div>`;
$('#main_div').append(html);
});
});
</script>
order.inc.php (php includes file) :
<?php
// Save Button
if (isset($_POST['submitOrder'])) {
// passenger
$p_name = $_POST['p_name'];
$ticket_no = $_POST['ticket_no'];
var_dump($p_name);
echo '<br/>';
var_dump($ticket_no);
echo '<br/>';
foreach ($p_name as $key => $value) {
echo $p_name[$key];
echo $ticket_no[$key];
echo "<br/>";
}
}
I solved my problem which returns whole array element to send to PHP includes file.
array(2) { [0]=> string(7) "6386868" [1]=> string(6) "868768" }
array(2) { [0]=> string(4) "6868" [1]=> string(4) "6868" }
The problem is the DOM element.
I don't put the <form> tag into currect place. When I click the add button, jquery is adding out of <form> tag.
Solution:
I changed the <form> tag outside of bootstrap <div> tag which works fine that returns whole array element.
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>
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(); //
});
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