On button click event, I add some text box in my web page, so now I want to get the value of that textbox which was entered by the user. How can I do this?
$(document).ready(function()
{
var max_fields = 100;
var wrapper = $("#test1");
var add_button = $("#eassy");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields)
{
//max input box allowed
x++;
$(wrapper).append('<div><input type="text" name="pay"></div>');
}
});
});
I use this to dynamically create textboxes. Please give me some guidelines!
You need give unique name to each textbox:
Do this:
if(x < max_fields){ //max input box allowed
$(wrapper).append('<div><input type="text" name="pay[]"></div>');
x++;
}
You will get the value of all textbox in array. You can see the value of each by:
print_r($_REQUEST['pay']);
This will be a array and can retrieve by:
foreach($_REQUEST['pay'] as $item){
echo $item;
}
Since there are many textboxes with same name, you should use array of names.
The append() call should be like this:
$(wrapper).append('<div><input type="text" name="pay[]"></div>');
And then in the back-end, you can do:
for($i = 0; $i < $max_fields; $i++)
if(isset($_POST['pay'][$i]))
$value = $_POST['pay'][$i]; // Use this value of the textbox
else
break;
EDIT
To get max_fields in PHP:
HTML:
<input type="hidden" id="inpMaxFields" name="inpMaxFields" value="">
JQuery:
$('#inpMaxFields').val(max_fields);
PHP:
$max_fields = $_POST['inpMaxFields'];
Related
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>
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.
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,
$(document).ready(function () {
var userSites = newArray();
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 5; //initial text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) {
x++; //text box increment
$(wrapper).append('<div><input type="text" name ="mytext[]"/>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 have this code, because I want to have a lot of user inputs. However, once the user inputs this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet, is that possible as well?
However, now that the user has input this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet?
When the form is submitted, the event handler, collectData gathers the text in each <input> and uses the push method to populate an array. This array is then stored in a hidden <input> and that data is then extracted by the form which then posts to the server.
I don't know much about Java applets but I got you this far. I suggest you ask about Java in a new question. Your tags are of a JavaScript/jQuery nature.
My demo actually functions with a test server so once submitted, the server will respond with the data that was posted to it.
This works: http://plnkr.co/edit/seD0L3oI7dTnXQrrFZPl?p=preview
Added Code
form.addEventListener('submit', collectData, false);
function collectData(e) {
var userSites = [];
var cache = document.getElementById('cache');
var z = 0;
while (z < max_fields) {
z++;
var data = inputs[z].val();
userSites.push(data);
}
e.stopPropagation();
cache.value = userSites;
}
});
Create an Array object in your one of you script tags :
<script type="text/javascript" >
var myArr=new Array();
</script>
Now add onchange to your inputs also update myArr :
$(wrapper).append('<div><input type="text" name ="myText'+x.toString()+'" onchange="myArr.push(this.value);document.getElementById('myArrInput').value=JSON.stringify(myArr);" /><a href="#" class="remove_field" onclick="myArr['+x.toString()+'].value=null;document.getElementById('myArrInput').value=JSON.stringify(myArr);" >Remove</a></div>');
Add this hiddenField to your page to send myArr to you applet as JSON string:
<input id="myArrInput" type="hidden" name="myArray" value="" />
In server you have to convert myArray Json string to object.
I have a problem with my registration form. So, I have some fields that are generetad when user click on link, and those fields are lost after I press form Submit button if validation fails. If validation pass, everything is correct and data is saved into database.
So these are that fields, and also script to add new field:
<script>
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var FacebookInputsWrapper = $("#FacebookInputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#FacebookAddMoreFileBox"); //Add button ID
var x = FacebookInputsWrapper.length; //initlal text box count
var FieldCount=0; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(FacebookInputsWrapper).append('<div style="margin-top:10px;"><input id="SocialMediaLink' + FieldCount + 'Link" type="hidden" name="data[SocialMediaLink][' + FieldCount + '][type]" value="fb" /><input id="SocialMediaLink' + FieldCount + 'Link" type="text" name="data[SocialMediaLink][' + FieldCount + '][link]" class="input-xlarge" placeholder="Facebook link" /><a style="background:0;color:black;" href="#" class="facebookremoveclass">×</a></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".facebookremoveclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
</script>
HTML
<li><label>Facebook</label>
<div >
<div style="float:right; margin-top:10px;" id="FacebookInputsWrapper"><?php echo $this->Form->input('SocialMediaLink.0.type',array('type'=>'hidden','value'=>'fb')); ?><?php echo $this->Form->input('SocialMediaLink.0.link',array('type'=>'text','class'=>'input-xlarge','label'=>false,'div'=>false,'placeholder'=>'Facebook link', 'error' => array(
'attributes' => array('class' => 'inputerror')
))); ?><label style="color:#FF0000;"><?php echo #$valid_social; ?></label>
<a style="margin-left:10px;background : 0;color:black;" href="#" id="FacebookAddMoreFileBox">Add another Facebook account</a></div>
</div>
So my question is: is it possible to save dynamically generated form fields and their values after validation fails and how?
Thank you
If I understand the question properly, you need to show those dynamically created fields in your view after validation has failed. Do it like this, checking $this->request->data for those fields:
<?if (!empty($this->request->data['SocialMediaLink'])):?>
<?foreach($this->request->data['SocialMediaLink'] as $i => $item):?>
<div style="margin-top:10px;">
<?=$this->Form->hidden('SocialMediaLink.' . $i . '.type', array('value' => 'fb'))?>
<?=$this->Form->input('SocialMediaLink.' . $i . '.link')?>
</div>
<?endforeach;?>
<?endif;?>
Alternatively, you could trigger the click event on AddButton the right amount of times on page load, based on the number of elements in $this->request->data['SocialMediaLink']