Adding dynamic form fields with JavaScript - javascript

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>

Related

how to add fields with increased number in name to a form using javascript?

I have a form that looks like this:
<form action="/a1/configurer/1" method="post">
<label>Fill out a revenue (such as "salary")</label>
<input type="text" name="revenu_0[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_0[amount]">
Add revenus
In this add_field() function I want to add this :
<label>Fill out a revenu</label>
<input type="text" name="revenu_1[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_1[amount]">
And when clicking the button again, name is "revenu_2" and so on (incrementing).
I have tried this:
function add_field() {
i = 1;
var extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
i = i + 1;
document.getElementsByTagName('body')[0].appendChild(extra);
}
That's only a very small part of the solution and obviously, this doesn't increment.
How do I do this?
You are pretty close. The important piece you're missing is to make sure i is declared outside the add_field function scope. Then, each time you call the function, the previous value of i will be persisted in the outer scope. See below for a working example.
let i = 1;
function add_field() {
const extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
extra.setAttribute("placeholder", "Field " + i);
document.getElementsByTagName('form')[0].appendChild(extra);
i = i + 1;
}
<button onclick="add_field()">Add field</button>
<form></form>
Solution #1
var i = 1;
btn.onclick = () => {
var label = document.createElement('label'),
input = document.createElement('input'),
br = document.createElement('br');
label.innerHTML = 'Label text ';
input.type = 'text';
input.name = 'revenu_' + i + '[category]';
input.placeholder = 'Field #' + i;
myForm.appendChild(label);
myForm.appendChild(input);
myForm.appendChild(br);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Solution #2
var i = 1;
btn.onclick = () => {
var add = `
<label>Fill out a revenu</label>
<input type="text" name="revenu_${i}[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_${i}[amount]">
<br>
`;
myForm.insertAdjacentHTML('beforeend', add);
console.log(add);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Notice that in both cases:
button must have id="btn";
form must have id="myForm".
Obviously, if you change those ids in the HTML code, you need to change them in the JS code as well.

how to get an array post values

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.

Add/Remove multiple inputs type text using jQuery

I'm trying to have two sections of inputs where users can add or remove a text box, this is how my code looks.
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = ('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/>remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
//$(wrapper).slideDown(800);
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value=""/>
add
</div>
</div>
</br>
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value=""/>
add
</div>
</div>
The "remove" link works, however when I try to add a text box, the text box is added in both sections. Is there a way of adding the text box only to the div where the "add" link is pressed from? Thank you.
$(this.parentElement).append(fieldHTML); // Add field html
Edited Answer so both can have up to 10:
`$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = ('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/>remove</div>'; //New input field html
$(addButton).click(function(){ //Once add button is clicked
var theWrapper = $(this).closest(wrapper);
var numOfChildren = theWrapper.children().length;
if( numOfChildren < maxField){ //Check maximum number of input fields
theWrapper.append(fieldHTML);
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});`
You could use jQuery's closest function - see this JSFiddle: https://jsfiddle.net/8sdpLy3L/
$(this).closest(wrapper).append(fieldHTML);
It's because your var wrapper = ('.field_wrapper'); //Input field wrapper is referencing the .field_wrapper class. So when you go to append with $(wrapper).append(fieldHTML); // Add field html It's adding it to both elements that have that class.
I would add an id to the wrapper you want to append the field to and separate click handlers for the add buttons, or perhaps a data attribute to the add buttons to point to the correct id.

Adding dynamic input based on one field that contains a sum of two other inputs

I am working on a form that sums two inputs and put the result of this sum in another input.
Input #1 is type number and it's called adult_qty
Input #2 is type number and it's called kid_pay_qty
The input that receives the sum is called qty_traveling.
This is the HTML
<form>
....
<label for "adult_qty">How many adults:</label><br/>
<input type="number" name="adult_qty" id="adult_qty" size="5" value="0">
<label for "kid_pay_qty">How many children:</label><br/>
<input type="number" name="kid_pay_qty" id="kid_pay_qty" size="5" value="0">
<label for "qty_traveling">Total of Pax:</label><br/>
<input type="text" name="qty_traveling" id="qty_traveling" size="5" value="0" readonly>
<p><h2>Other Pax Information</h2></p>
<div class="input_fields_wrap">
</div>
....
</form>
Then I have a JQuery that will calculate the two inputs and attribute the result to the third input. So far it is working very good.
Finally I am trying to add to this form dynamic inputs called First Name and Last Name inside of a div called input_field_wrap in the same amount displayed on the sum of the two inputs.
Let's say that the result is two, I would like to have two First Name and two Last Name inputs added to the form dynamically. Whatever is the result, I would like to have this amount added dynamically as soon as the sum is given to the "qty_traveling" input.
Please see below my JQuery script:
$(document).ready(function() {
$('#adult_qty').keyup(function() {
updateTotal();
});
$('#kid_pay_qty').keyup(function() {
updateTotal();
});
});
function updateTotal() {
var input1 = parseInt($('#adult_qty').val());
var input2 = parseInt($('#kid_pay_qty').val());
var total = input1 + input2;
$('#qty_traveling').val(total);
var max_fields = total; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var x = 1; //initlal text box count
while(x < max_fields){
e.preventDefault();
x++; //text box increment
$(wrapper).append('<div><div id="left_col"><label for "otherFirstname[]">First Name:</label></div><div id="right_col"><input type="text" name="otherFirstname[]" id="otherFirstname"/></div></div>'); //add input box
$(wrapper).append('<div><div id="left_col"><label for "otherLastname[]">Last Name:</label></div><div id="right_col"><input type="text" name="otherLastname[]" id="otherLastname"/></div></div>'); //add input box
}
};
};
The sum is working perfectly and it gets updated as the Keyup determines but the inputs are not being added to the form.
Thanks in advance for any help.
First, e.preventDefault() is breaking your code. And you need to change you condition in the while loop. Since 2 < 2 is always false in you 2nd or last loop if your total is 2.
Make sure you empty wrapper's content before you append the inputs. You can use jQuery empty() to your code.
Working Demo.
Change your function:
function updateTotal() {
var input1 = parseInt($("#adult_qty").val());
var input2 = parseInt($("#kid_pay_qty").val());
var total = input1 + input2;
$("#qty_traveling").val(total);
var max_fields = total; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var x = 1; //initlal text box count
$(wrapper).empty();
while (x <= max_fields) {
//e.preventDefault();
x++;
//text box increment
$(wrapper).append(
'<div><div id="left_col"><label for "otherFirstname[]">First Name:</label></div><div id="right_col"><input type="text" name="otherFirstname[]" id="otherFirstname"/></div></div>'
); //add input box
$(wrapper).append(
'<div><div id="left_col"><label for "otherLastname[]">Last Name:</label></div><div id="right_col"><input type="text" name="otherLastname[]" id="otherLastname"/></div></div>'
); //add input box
}
}
Also, make sure you ids are unique.

datepicker used in textbox inside script

when I use date picker in text box outside script it works fine, iwhich looks like this.
<input type="text" id="entry_date" name="entry_date[]" class="form-control datepicker" data-date-format="<?= config_item('date_picker_format'); ?>" value=""/>
But when I use same date picker function inside script it's not working and I don't know whether it will work like this what the way I gave.Here is my code
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#datepicker1").datepicker();
});
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div class="form-group"><input class="form-control date_pick datepicker col-lg-2" id="datepicker1" placeholder="yyyy-mm-dd" type="text" name="entry_date[]" value=""/></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
});
</script>
Can You please explain to me howI should call this date picker?
Thank You
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<button class="add_button">Add</button>
<div class="field_wrapper"></div>
<script type="text/javascript">
$(document).ready(function () {
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = ''; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
fieldHTML = '<div class="form-group"><input class="form-control date_pick datepicker col-lg-2" id="datepicker' + x + '" placeholder="yyyy-mm-dd" type="text" name="entry_date[]" value=""/></div>';
$(wrapper).append(fieldHTML); // Add field html
$("#datepicker" + x).datepicker();
}
});
});
</script>
Check html appended properly, or put html code separate to jquery, maybe using jquery code appended lately when datepicker function work.
Regards,

Categories

Resources