datepicker used in textbox inside script - javascript

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,

Related

Jquery - Variable not updating into another variable

first of all i'm not a programmer of any kind, so i please need you to fix my issue.
I have a contact form which have inside a place where i can add more input fields till a maximum of 10.
Each field i add it has inside the code a class that i called "pers", and i want that this class pers has an incremental number near to it, as pers1, 2, 3 and so go on.
Getting the incremental value was easy but the problem is that the class "pers" wont update the variable keeping the first number on document load.
Here is the code
<script type="text/javascript">
window.s = 1;
</script>
<script type="text/javascript">
$(document).ready(function() {
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var maxField = 10;
var fieldHTML = '<div style="margin-top:5px;"><input type="text3" name="pers' + window.s + '" placeholder="Nome e Cognome"/><input type="time" style=margin-left:3.5px; autocomplete="off"><input type="time" style=margin-left:3.5px; autocomplete="off"><img src="IMG/less_icon.png"></div>';
$(addButton).click(function() {
if (window.s < maxField) {
window.s++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
s--; //Decrement field counter
});
});
</script>
There is a global variable "window.s" because it was my last try to get the var updated.
The fields adds correctly till 10 as it should be, but the "window.s" or when it was only "s" still keeps his first value of 1, and so "pers" is always "pers1". I thought that exposing a global variable i would have fix the problem, but nothing.
What am i doing wrong?
Thank you very much for your help guys.
The problem with your code is because you only set fieldHTML once, when the page loads. At this point window.s is 1, so this is the value that's used every time you reference fieldHTML. The quick fix to this would be to put the fieldHTML definition inside the click() event handler.
However the better approach it to entirely remove the need for the incremental variable at all. Use the same name on all the fields you dynamically generate. This way you don't need to maintain the count (eg. if there have been 5 added and someone deletes the 3rd one, you'll currently end up with 2 per5 elements). Because of this it also simplifies the JS logic. In addition you should put the HTML to clone in a <template> element, not the JS, so that there's no cross-contamination of the codebase.
Here's a working example of the changes I mention:
jQuery($ => {
var $addButton = $('.add_button');
var $wrapper = $('.field_wrapper');
var maxFields = 10;
var fieldHTML = $('#field_template').html();
$addButton.click(() => {
if ($('.field_wrapper > div').length < maxFields) {
$wrapper.append(fieldHTML);
}
});
$wrapper.on('click', '.remove_button', e => {
e.preventDefault();
$(e.target).closest('div').remove();
});
});
.field_wrapper>div {
margin-top: 5px;
}
.field_wrapper input.time {
margin-left: 3.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="add_button">Add</button>
<div class="field_wrapper"></div>
<template id="field_template">
<div>
<input type="text3" name="pers[]" placeholder="Nome e Cognome" />
<input type="time" name="time1[]" class="time" autocomplete="off" />
<input type="time" name="time2[]" class="time" autocomplete="off" />
<a href="#" class="remove_button" title="Rimuovi">
<img src="IMG/less_icon.png">
</a>
</div>
</template>
You can then receive all the input values as an array in your PHP code, like this.
It's because you have not used the updated value there.
First, you assign a value to window.s, and then you create a variable that uses the value of window.s from the initial state, and on each addition, it just appends the same fieldHtml. So, you are getting the same value.
Here is the answer, you are looking:
<div><button class="add_button">click me</button></div>
<div class="field_wrapper"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
window.s = 1;
</script>
<script type="text/javascript">
$(document).ready(function() {
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var maxField = 10;
$(addButton).click(function() {
if (window.s < maxField) {
window.s++; //Increment field counter
let fieldHTML = generateLine(window.s);
$(wrapper).append(fieldHTML); //Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
s--; //Decrement field counter
});
});
function generateLine(lineNumber){
return '<div style="margin-top:5px;"><input type="text3" name="pers' + lineNumber + '" placeholder="Nome e Cognome"/><input type="time" style=margin-left:3.5px; autocomplete="off"><input type="time" style=margin-left:3.5px; autocomplete="off"><img src="IMG/less_icon.png"></div>';
}
</script>

Read data from Javascript dynamic input in node.js

I need dynamic input fields for my node-js application. I need to populate a input text are for writing their cost names on a form. I found some javascript code on internet. It works perfectly but when i try to read data from body, i only have one value. What could be the reason?
Here is my javascript code;
$(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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><input type="text" name="generalCostName[]" class="form-control"/>Remove</div>'
); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) {
//user click on remove text
e.preventDefault();
$(this).parent("div").remove();
x--;
});
});
here is the part of my ejs file;
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button><div>
<input type="text" name="generalCostName[]" class="form-control"></div>
</div>
For example, i populate 2 more input fields and their values are "Test1","Test2" and "Test3". When i submit values to the node-js side, on the console( console.log(req.body.generalCostName) ) i only have Test1 value. What could be the reason?
You need to use formData to send your dynamically added element to your backend node.js. We need to use jQuery $.each function to get all the values of the input you will added.
Once we have all the value we can append them to the formData which will send via ajax or axios to the backend.
I have limited the max fields added to 3 so for demo purposes but you can use as many as you like. As soon as you hit submit - the data will be stored in the formData and then you can do POST request to node.js where you can see all this coming.
Demo: (Shows all the inputs added and their value stored in the formData)
$(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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><input type="text" name="generalCostName" class="form-control"/>Remove</div>'
); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) {
//user click on remove text
e.preventDefault();
$(this).parent("div").remove();
x--;
});
});
//Send data to node.js
function sendData() {
//initialize formData
var formData = new FormData();
//Get all value of dynamically added elements
$('.form-control').each(function(index, item) {
var val = $(item).val();
//Append Data
formData.append('value[]', val)
});
// Display the key/value pairs for formData
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="generalCostName[]" class="form-control"></div>
</div>
<br>
<button onclick="sendData()">
Submit
</button>

Adding dynamic form fields with 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>

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.

Categories

Resources