In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.
Related
EDIT: I have updated the code with the answers.
I have a increment function that is working fine. However:
1. I would like to set some limits based on the total number available in one of the span. For example, 10. So the incrementing can't be more than 10. #DONE
Another issue is that I am planning to have multiple rows and before I save I want to make sure if we count the increments in every row it should not be more than 10 as well. If it decrease the total number (span) dynamically would be nice.
I'm adding rows dynamically with the ADD button, how can I add news rows that actually work with the current functions? Mine rows just clone the first one and the increment function is disabled.
document.addEventListener('DOMContentLoaded', async function() {
document.querySelector('#addlocationdest').addEventListener('click', add);
});
function add() {
var x = 1;
var container = document.getElementById('destination');
var detail = document.getElementById('row');
var clone = detail.cloneNode(true);
clone.id = "destination" + x;
x++;
container.appendChild(clone);
}
window.addEventListener("load", () => {
let elTotalQuantity = document.querySelector("#totalqty");
let totalQuantity = parseInt(elTotalQuantity.innerHTML);
function getSumOfRows() {
let sum = 0;
for (let input of document.querySelectorAll("form .row > input.quantity"))
sum += parseInt(input.value);
return sum;
}
for (let row of document.querySelectorAll("form .row")) {
let input = row.querySelector("input");
row.querySelector(".increment").addEventListener("click", () => {
if (getSumOfRows() >= totalQuantity) return;
input.value++;
elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
});
row.querySelector(".decrement").addEventListener("click", () => {
if (input.value <= 0) return;
input.value--;
elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
});
}
});
<div id="location" class="hide">
<div class="title">Transfer details</div><br>
<div class="line padded-s">Total Quantity: <span>10</span></div>
<br>
<form>
<label>New Total Quantity at this location: <span id="totalqty">10</span></label>
<br>
<div id="destination">
<div id="row" class="row">
<button type="button" class="decrement">-</button>
<input type="text" class="quantity" value="0" readonly/>
<button type="button" class="increment">+</button>
<a>Location: </a>
<input type="text" class="location" value="0" readonly/>
</div>
</div>
</form>
<label>Total being transfer: <p id="total-sum"></p></label>
<br>
<button type="button" id="addlocationdest">ADD</button>
<button type="button" id="removelocationdest">REMOVE</button>
</div>
Prologue
As long as the total quantity is fixed at the beginning of the script-execution, this works. Otherwise, it would be best to save the actual allowed total quantity as an attribute, and observe it using a MutationObserver. That way you can update your max. value in your code dynamically, when the total quantity-attribute changes. You can define custom attributes by naming them "data-*" where "*" is a custom name.
Solution for your problem
You are using the same ID on multiple elements. What you meant were classes, so change id="increment" to class="increment", and the same for decrement.
Since we don't want to input something with the buttons, but add listener to them, I'd say it is better to actually use <button>. In forms, buttons act as type="submit", which we don't want, so we need to change it to type="button".
Since the rows and the total quantity actually belong together, it is wiser to place them together into one <form>-element. However, you can still group the buttons and inputs as a row together using <div>.
Now regarding the in-/decrementing of the row's values and the total quantity:
Save the allowed total quantity in a variable
Add event-listener to the corresponding buttons
If action is valid, change row's value
Update total quantity number to totalQuantity - getSumOfRows()
To add new rows dynamically, we create and setup such an element, and append it to the form. See the appendNewRow()-function below.
Sidenote
I have added the readonly attribute to the input-fields so that you cannot enter numbers via keyboard.
window.addEventListener("load", () => {
let elTotalQuantity = document.querySelector("#totalqty");
let totalQuantity = parseInt(elTotalQuantity.innerHTML);
function getSumOfRows() {
let sum = 0;
for (let input of document.querySelectorAll("form .row > input.quantity"))
sum += parseInt(input.value);
return sum;
}
function updateTotalQuantity() {
elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
}
function appendNewRow() {
let row = document.createElement("div");
row.classList.add("row");
let child;
// input.quantity
let input = document.createElement("input");
input.classList.add("quantity");
input.value = "0";
input.setAttribute("readonly", "");
input.setAttribute("type", "text");
row.append(input);
// button.increment
child = document.createElement("button");
child.classList.add("increment");
child.innerHTML = "+";
child.setAttribute("type", "button");
child.addEventListener("click", () => {
if (getSumOfRows() >= totalQuantity) return;
input.value++;
updateTotalQuantity();
});
row.append(child);
// button.increment
child = document.createElement("button");
child.classList.add("decrement");
child.innerHTML = "-";
child.setAttribute("type", "button");
child.addEventListener("click", () => {
if (input.value <= 0) return;
input.value--;
updateTotalQuantity();
});
row.append(child);
// button.remove-row
child = document.createElement("button");
child.classList.add("remove-row");
child.innerHTML = "Remove";
child.setAttribute("type", "button");
child.addEventListener("click", () => {
row.remove();
updateTotalQuantity();
});
row.append(child);
document.querySelector("form .rows").append(row);
}
document.querySelector("form .add-row").addEventListener("click", () => appendNewRow());
appendNewRow();
});
<form>
<label>Total Quantity: <span id="totalqty">10</span></label>
<br>
<div class="rows">
</div>
<button type="button" class="add-row">Add new row</button>
</form>
QuerySelector only selects the first occurrence so you haven't really added a listener to the second "row". You should use querySelectorAll but, instead of unique ids, use classes.
<input class="increment" type="button" value="+" />
Now you can use document.querySelectorAll(".increment") to get all elements in an array.
You can traverse in the DOM by using parentElement. By knowing which button you clicked, you can traverse up to the form element and then select the first child - which is an input. A more dynamic way would be to use querySelector to select the input, in case the HTML change in the future. Anyway, that's how you can know which input to manipulate based on where the buttons are in the DOM.
I added two global variables, totalSum and maxSum. maxSum is fetched from your span element (which I assigned an unique id to). totalSum makes sure that all inputs combined doesn't exceed maxSum.
You had some duplicate code, so I refactored it into a new method: changeValue.
In all, I think the code speaks for itself.
Oh, this code doesn't take into account that the user can change the value inside the input. I will leave that for you to figure out with an "oninput" listener on each text input.
var totalSum = 0; // 3
var maxSum = 0
var totalSumElement = null;
document.addEventListener('DOMContentLoaded', async function() {
totalSumElement = document.getElementById('total-sum');
maxSum = document.getElementById('max-sum').innerText;
var incrementElements = document.querySelectorAll('.increment'); // 1
var decrementElements = document.querySelectorAll('.decrement');
addListener('click', incrementElements, incrementValue);
addListener('click', decrementElements, decrementValue);
});
function addListener(type, elementArr, func) {
for (element of elementArr) {
element.addEventListener(type, func);
}
}
function withinRange(newValue) {
var maxReached = newValue > maxSum; // 3
var zeroReached = newValue < 0;
return !maxReached && !zeroReached;
}
function changeValue(event, change) { // 4
if (withinRange(totalSum + change)) {
let parent = event.currentTarget.parentElement; // 2
let input = parent.children[0];
let value = parseInt(input.value) || 0;
if (withinRange(value + change)) {
input.value = value + change;
totalSum = totalSum + change;
}
}
totalSumElement.textContent = `Total: ${totalSum}`;
}
function incrementValue(event) {
changeValue(event, 1);
}
function decrementValue(event) {
changeValue(event, -1);
}
#totalqty {
padding-bottom: 1rem;
}
<div id="totalqty" class="line padded-s">Total Quantity: <span id="max-sum">10</span></div>
<form>
<input type="text" value="0" />
<input class="increment" type="button" value="+" />
<input class="decrement" type="button" value="-" />
</form>
<form>
<input type="text" value="0" />
<input class="increment" type="button" value="+" />
<input class="decrement" type="button" value="-" />
</form>
<p id="total-sum"></p>
How can I check the Number of Incomplete Input fields in Particular ID, (form1, form2).
If 2 input fields are empty, in i want a msg saying something like "Incomplete Input 2"
How is it Possible to do this in JS ?
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test">
<input type="text" value="">
</div>
This is the JS, which is working, i have have multiple JS with class named assigned to each inputs and get the value, but i need to make this check all the Input fields inside just the ID.
$(document).on("click", "#form1", function() {
var count = $('input').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
Your html structure, especially form structure is not correct, so you should first add some submit button to form that can be clicked. Then you can add event listener on form's submission. In the event handler you should select children inputs inside the form tag using $(this).children("input"). Now you can filter them.
$(document).on("submit", "#form1", function (e) {
e.preventDefault();
var count = $(this)
.children("input")
.filter(function (input) {
return $(this).val() == "";
}).length;
alert(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
<button type="submit">Submit</button>
</form>
This is the JS, which is working, if I have have multiple JS with class named assigned to each inputs and Im getting the value, but i have multiple JS for this to work.
How can i make this Simpler say like, when user clicks on Div, it only checks the input fields inside that div.
$(document).on("click", "#form1", function() {
var count = $('.input_field1').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
HTML
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="" class="input_field1">
<input type="text" value=""class="input_field1">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test" class="input_field2">
<input type="text" value="" class="input_field2">
</div>
See snippet below:
It has commented and if you put some effort on it, you can have a jQuery plugin out of it.
(function () {
'use strict';
var
// this use to prevent event conflict
namespace = 'customValidation',
submitResult = true;
var
input,
inputType,
inputParent,
inputNamePlaceholder,
//-----
writableInputTypes = ['text', 'password'],
checkboxInputType = 'checkbox';
var
errorContainerCls = 'error-container';
// Add this function in global scope
// Change form status with this function
function changeFormStatus(status) {
submitResult = submitResult && status;
}
// Check if a radio input in a
// group is checked
function isRadioChecked(form, name) {
if(!form || !name) return true;
var radio = $(form).find('input[type="radio"][name="' + name.toString() + '"]:checked');
return typeof radio !== 'undefined' && radio.length
? true
: false;
}
function eachInputCall(inp, isInSubmit) {
input = $(inp);
inputType = input.attr('type');
// assume that we have a name placeholder in
// attributes named data-name-placeholder
inputNamePlaceholder = input.attr('data-name-placeholder');
// if it is not present,
// we should have backup placeholder
inputNamePlaceholder = inputNamePlaceholder ? inputNamePlaceholder : 'input';
if(!inputType) return;
// you have three type of inputs in simple form
// that you can make realtime validation for them
// 1. writable inputs ✓
// 2. checkbox inputs ✓
// 3. radio inputs ✕
// for item 3 you should write
// another `else if` condition
// but you should have it for
// each name (it was easier if it was a plugin)
// radio inputs is not good for realtime
// unchecked validation.
// You can check radios through submit event
// let make it lowercase
inputType = inputType.toLowerCase();
// first check type of input
if ($.inArray(inputType, writableInputTypes) !== -1) {
if(!isInSubmit) {
input.on('input.' + namespace, function () {
writableInputChange(this);
});
} else {
writableInputChange(inp);
}
} else if ('checkbox' == inputType) { // if it is checkbox
if(!isInSubmit) {
input.on('change.' + namespace, function () {
checkboxInputChange(this);
});
} else {
checkboxInputChange(inp);
}
}
}
// Check if an input has some validation
// (here we have just required or not empty)
function writableInputChange(inp) {
// I use $(this) instead of input
// to prevent conflict if selector
// is a class for an input
if('' == $.trim($(inp).val())) {
changeFormStatus(false);
// your appropriate message
// you can use bootstrap's popover
// to modefy just input element
// and make your html structure
// more flexible
// or
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(inp).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please fill ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(inp).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
// Check if an checkbox is checked
function checkboxInputChange(chk) {
if(!$(chk).is(':checked')) {
changeFormStatus(false);
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(chk).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please check ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(chk).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
$(function () {
var
form = $('#form'),
// you can change this selector with your classes
formInputs = form.find('> .input-group > input');
formInputs.each(function () {
eachInputCall(this);
});
form.submit(function () {
submitResult = true;
// check all inputs after form submission
formInputs.each(function () {
eachInputCall(this, true);
});
// Because of radio grouping by name,
// we should select them separately
var selectedGender = isRadioChecked($(this), 'gender');
var parent;
if(selectedGender) {
changeFormStatus(true);
parent = $(this).find('input[type="radio"][name="gender"]').parent();
parent.children('.' + errorContainerCls).remove();
} else {
changeFormStatus(false);
// I assume that all radios are in
// a separate container
parent = $(this).find('input[type="radio"][name="gender"]').parent();
if(!parent.children('.' + errorContainerCls).length) {
parent.append($('<div class="' + errorContainerCls + '" />').text('Please check your gender'));
}
}
if(!submitResult) {
console.log('There are errors during validations!');
}
return submitResult;
});
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<div class="input-group">
<input type="text" name="input1" data-name-placeholder="name">
</div>
<div class="input-group">
<input type="checkbox" name="input2" data-name-placeholder="agreement">
</div>
<div class="input-group">
<input type="radio" name="gender">
<input type="radio" name="gender">
</div>
<button type="submit">
submit
</button>
</form>
I have a website where you can enter text into an input field, and press "Add new row" to add another input field.
When the user presses the submit button, I want to be able to read all of the text inside of the text field, but I can't seem to figure out how to access the text within the text fields.
Here is my code:
<head>
<script src = "https://code.jquery.com/jquery-3.3.1.min.js"
crossorigin="anonymous"> </script>
</head>
<script type ="text/javascript">
var array = []
var track = 0;
$(document).on("click", ".btn-add-row", function(){
var row = $(".row").eq(0).clone().show();
$(".element-wrapper").append(row);
var ye = $(".element-wrapper")
})
$(document).on("click", ".btn-remove-row", function(){
var index = $(".btn-remove-row").index(this);
$(".row").eq(index).remove();
})
</script>
<body>
<h1>upload file</h1>
<form method = "post" enctype="multipart/form-data" action = "/">
<input type = "file" name = "filename">
<input type = "submit" value = "upload">
</form>
<div class = "element-wrapper">
<div class = "row" style = "display: none;">
<input type = "text" placeholder = "Attribute" id = "ye">
<button class = "btn-remove-row">
Remove Row
</button>
</div>
</div>
<button class = "btn-add-row"> Add New Row </button>
</body>
</html>
And here is a CodePen to go along with it:
https://codepen.io/etills/pen/qBdEKPV
Would appreciate it if someone could tell me how to read all the text from the input rows when the user presses submit.
I ultimately want to put the text into an array and make a .txt file with that text that is entered.
Thanks
You need this selector to capture only the visible textboxes:
div.row:not([style='display: none;']) input[type=\"text\"]"
Something like this:
$("form").on("submit", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("div.row:not([style='display: none;']) input[type=\"text\"]");
var len = inputs.length;
for (var i = 0; i < len; i++) {
array.push({
input: i,
value: inputs[i].value
});
}
console.log(array);
});
You'll get this result:
See in this example:
$(function() {
var array = [];
var track = 0;
$(document).on("click", ".btn-add-row", function() {
var row = $(".row").eq(0).clone().show();
$(".element-wrapper").append(row);
var ye = $(".element-wrapper")
});
$(document).on("click", ".btn-remove-row", function() {
var index = $(".btn-remove-row").index(this);
$(".row").eq(index).remove();
});
$("form").on("submit", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("div.row:not([style='display: none;']) input[type=\"text\"]");
var len = inputs.length;
for (var i = 0; i < len; i++) {
array.push({
input: i,
value: inputs[i].value
});
}
console.log(array);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>upload file</h1>
<form method="post" enctype="multipart/form-data" action="/">
<input type="file" name="filename">
<input type="submit" value="upload">
</form>
<div class="element-wrapper">
<div class="row" style="display: none;">
<input type="text" placeholder="Attribute">
<button class="btn-remove-row">
Remove Row
</button>
</div>
</div>
<button class="btn-add-row"> Add New Row </button>
Remember: Element Id must be unique in a page. Avoid using the same id="ye" in <input type="text" placeholder="Attribute" id="ye">.
On submit check for all the inputs that you want and collect their values.
$(document).on("click", "input[type=submit]", function(e){
e.preventDefault()
$('input[type=text]').each((i, input) => {
console.log(input.value)
})
})
Example: https://codepen.io/jzabala/pen/vYOErpa?editors=1111
I am trying to make a form field that asks the user which countries it has visited, and limit this to 10. So the user has to give ten inputs in one form field.
But when I click on the submit button it won't let the user enter a second time. It just calls the function that displays the first country that the user has entered.
How do I keep the values the user is entering in the form field and when the user has entered all the ten countries, then click on submit to call the function that would display all the countries?
function validateForm() {
var repeat = new Array();
for (i = 0; i < 10; i++) {
var x = document.forms["form1"]["countries"].value;
repeat.push(x);
}
document.write(repeat);
}
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" onclick="validateForm()" value="Click Me!">
It keeps on displaying that one country the user has entered 10 times, instead of letting user enter ten countries and then displaying then when clicking on submit.
This will do what you sketched out. I don't think it's a very good way of asking a user for 10 items, as there's no feedback as to how many they've entered, nor the ability to edit the items once entered, nor a way of clearing the list to enter 10 more. Also, this will never actually submit the list. But this meets the requirements as stated:
var repeat = [];
function validateForm() {
var countries = document.getElementById("countries");
if (repeat.length < 10) {
var x = countries.value;
repeat.push(x);
countries.value = "";
countries.focus();
}
if (repeat.length === 10) {
var hid = document.getElementById("list");
hid.value = repeat.join('|');
console.log(hid.value);
var ul = document.getElementById("display");
ul.innerHTML = "";
for (var i = 0; i < 10; i++) {
ul.innerHTML += `<li>${repeat[i]}</li>`;
}
document.getElementById("done").style.display = "block";
}
}
window.onload = function() {
document.getElementById("click").addEventListener("click", validateForm);
};
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" id="click" value="Click Me!">
<input type="hidden" id="list" name="listOfCountries">
</form>
<br>
<div id="done" style="display:none">
Countries entered:
<ul id="display"></ul>
</div>
Note that the hidden fields listOfCountries will contain the list of 10 countries, delimited by a pipe symbol "|". It's up to you to post that to a server.
You could use a global array for the countries and store until ten countries in the array.
function enterCountry() {
var input = document.getElementById('country');
if (input.value && countries.length < 10) {
countries.push(input.value);
input.value = '';
input.placeholder = 'insert ' + (10 - countries.length);
}
if (countries.length === 10) {
input.placeholder = 'ready';
document.getElementById('allCountries').innerHTML = countries.join(', ');
}
}
var countries = [];
<form id="form1">
Enter the countries:
<input type="text" id="country" placeholder="insert 10"><br><br>
<input type="button" onclick="enterCountry()" value="Click Me!">
</form>
<div id="allCountries"></div>
Hey you can get multiple input value on submit with jquery
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
I have a form that is used to create a JSON array, see my previous question for reference.
In this form a user can add additional details to the fom by clicking a button and filling in said extra details.
These would then be placed into an array in a similar fashion to the below:
<input type="text" name="AdditionalCitizenship[0][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[0][TaxIdentificationNumber]">
<input type="text" name="AdditionalCitizenship[1][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[1][TaxIdentificationNumber]">
This would allow me to grab as many details as the user entered by incrementing the array index.
I was handed this script to add extra form fields.
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap_tel"); //Fields wrapper
var add_button = $(".add_field_button_tel"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><div class="row"><div class="form-group col-md-4"><label for="AdditionalTelephoneType">Telephone Type</label><input type="text" class="form-control" name="AdditionalTelephoneType[]" ></div><div class="form-group col-md-4"><label for="AdditionalTelephoneDialingCode">Dialing Code</label><input type="text" class="form-control" name="AdditionalTelephoneDialingCode[]"></div><div class="form-group col-md-4"><label for="AdditionalTelephoneNumber">Telephone Number</label><input type="text" class="form-control" name="AdditionalTelephoneNumber[]" ></div></div>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I am trying to use as is but in this scenario, it is difficult to increment x within the created HTML as it seems to blow up the function.
Could I create the HTML more iteratively like so:
First, create the DIV structure as a wrapper like:
var html = "<div></div>"
Then append an input to this variable called input
var input = document.createElement("input");
input.type = "text";
input.name = "AdditionalTelephoneType[" + x"]";
... and then insert the whole HTML block by using wrapper.append with the variables I have created previously?
You can find the highest x dynamically, see comments:
$("#add").on("click", function() {
// Get the containing form
var form = $(this).closest("form");
// Get all the AdditionalCitizenship fields from it using ^=, see
// https://www.w3.org/TR/css3-selectors/#attribute-substrings
var fields = form.find("input[name^=AdditionalCitizenship]");
// Find the one with the highest [x]
var x = fields.get().reduce((x, element) => {
var thisx = element.name.match(/AdditionalCitizenship\[(\d+)\]/);
if (thisx) {
thisx = +thisx[1]; // The capture group, convert to number
if (x < thisx) {
x = thisx;
}
}
return x;
}, 0);
// Add one
++x;
// Use x
console.log("Next x is " + x);
form.append('<input type="text" name="AdditionalCitizenship[' + x + '][CountryOfResidency]">');
form.append('<input type="text" name="AdditionalCitizenship[' + x + '][TaxIdentificationNumber]">');
});
<form>
<input type="text" name="AdditionalCitizenship[0][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[0][TaxIdentificationNumber]">
<input type="text" name="AdditionalCitizenship[1][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[1][TaxIdentificationNumber]">
<input type="button" id="add" value="Add">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>