I am trying to add dynamic fields on click and want to fetch each input box value that user types. Here is my working code.
HTML code
<div class="input_fields_wrap">
<div><input type="text" name="mytext"> <button class="add_field_button">Add More Fields</button>
</div>
</div>
JS code
$(document).ready(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><tr><td><input type="text" name="textbox' + x + '" id="removeId' + x + '" value="' + x + '" ></td><td><button class="remove_field" >Remove</button><button class="save_field" >save</button></td></tr></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
$(wrapper).on("click",".save_field", function(e){ //user click on remove text
e.preventDefault();
//Here on click of each save button I wanna grab particular text box value that user types in
})
});
On each click of add more fields I get new text box along with remove and save button, upon clicking on save button I want to grab its respective text box value that user has typed.
JSFiddle
PFB code , hope it helps
$(document).ready(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><tr><td><input type="text" name="textbox' + x + '" id="removeId' + x + '" value="' + x + '" ></td><td><button class="remove_field" >Remove</button><button class="save_field" >save</button></td></tr></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
$(wrapper).on("click", ".save_field", function(e) { //user click on remove text
var inpVal = $(this).siblings('input').val();
alert('inp value is :' + inpVal);
e.preventDefault();
//Here on click of each save button I wanna grab particular text box value that user types in
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<div>
<input type="text" name="mytext">
<button class="add_field_button">Add More Fields</button>
</div>
</div>
clicked button is sibling of required input tag. you can use .siblings('input') or .prevAll('input') to target input element along with .val() to get its value:
$(this).siblings('input').val();
Handler:
$(wrapper).on("click",".save_field", function(e){ //user click on remove text
e.preventDefault();
alert($(this).siblings('input').val());
//Here on click of each save button I wanna grab particular text box value that user types in
});
Working Demo
you can give dynamic id to your textboxes replace:
id="removeId'
with
id="removeId'+k
And then you can access them using
$("#id").val();
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'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.
I want to organize my DOM HTML elements so that they appear like this:
ADD AUTHOR (Button) // adds a whole new author
(textbox for field) //New Author
ADD BOOK (Button) // adds new textfields under this author
(textbox for field)
(textbox for field)
(textbox for field)
//I want to be able to add more books here with DOM if it's from the same author
(textbox for field) //New Author
ADD BOOK (Button) // adds new textfields under this author
(textbox for field)
(textbox for field)
//I want to be able to add more books here with DOM if it's from the same author
But what it does is:
ADD AUTHOR (Button)
(textbox for field)
ADD BOOK (Button)
(textbox for field)
(textbox for field)
(textbox for field)//this can be a new author or a authors' book
(textbox for field)
(textbox for field)
(textbox for field) // there is no structure
I am trying to send this code by post to another .php so that I can insert into my database. Does this mean that the post will be a array of an array. So will I read it as post['myBooksText['0']']?
This is the code that I have so far:
<form action="insertIntoDB.php" method="post">
<div class="input_fields_wrap">
<button class="add_field_button">Add Author</button>
<div><input type="text" name="myAuthorText[]"></div>
<button class="add_sub_field_button">Add Author Books</button>
<div><input type="text" name="myBooksText[]"></div>
</div>
</form>
<SCRIPT language="javascript">
$(document).ready(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 add_subButton = $(".add_sub_field_button"); //Add sub 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="myAuthorText[]"/>Remove</div>'); //add input box
}
});
$(add_subButton).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="myBooksText[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</SCRIPT>
I have a problem with the deleting function, is my code wrong or something? The add function is working fine though..........
plus how to insert the data from the added input field into the
database?
<script>
$(document).ready(function()
{
var max_fields = 25;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1; //initial text box count
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label for="no_telefon">No.Telefon: </label><input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: </label><input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<label for="no_telefon">No.Telefon:</label> <input type="text" id="no_telefon" name="no_telefon" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')" required/>
<label for="lokasi">Lokasi:</label> <input type="text" id="lokasi" name="lokasi" class="required input_field" required/>
</div>
</fieldset>
the sql.......
<?php
require("dbase.php");
if ($_POST) {
$id_akaun = isset($_POST['id_akaun']) ? $_POST['id_akaun'] : '';
$daerah = isset($_POST['daerah']) ? $_POST['daerah'] : '';
$kategori_akaun = isset($_POST['kategori_akaun']) ? $_POST['kategori_akaun'] : '';
$bahagian = isset($_POST['bahagian']) ? $_POST['bahagian'] : '';
$jenis = isset($_POST['jenis']) ? $_POST['jenis'] : '';
$no_telefon = isset($_POST['no_telefon']) ? $_POST['no_telefon'] : '';
$lokasi = isset($_POST['lokasi']) ? $_POST['lokasi'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
$sql = mysql_query("INSERT INTO maklumat_akaun VALUES ('', '$id_akaun' , '$daerah' , '$kategori_akaun' , '$bahagian' )");
$sql = mysql_query("INSERT INTO detail_akaun VALUES ('', '$jenis' , '$no_telefon' , '$lokasi', '".mysql_insert_id()."' )");
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='lamanutama.php'</script>";
}
?>
The parent of the clicked button is not div so this expession $(this).parent('div').remove(); does nothing. Use closest method instead:
$('fieldset').on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).closest('div').remove();
x--;
});
Demo: http://jsfiddle.net/11jdyrdf/
PFB code , hope it helps . The problem i feel was you were binding click event for remove on document.ready so at that point of time that anchor for remove was not created as it's being created on add , so click event was not getting binded. Have binded it on add handler.
$(document).ready(function()
{ var max_fields = 25; var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button");
var x = 1; //initial text box count
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label for="no_telefon">No.Telefon: <input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: <input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box
}
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent().parent().remove(); x--;
});
});
});
You haven't put closing tag of label
Make your code perfect you have written wrong code..
Replace your appending code with this one
and then parent() will work
$(wrapper).append('<div><label for="no_telefon">No.Telefon: </label><input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: </label><input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box
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']