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
Related
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.
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>
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 have a webpage in which there is a form with diffrent elements, in that there is also a Textfield which searches the names from the database and display it in a dropdown fashion.
Below that there is one more field that which is a button , through which i can add new TextField , same as above.
In that newly added TextField, I want the same AutoComplete feature as done above.
I have given the class names all correct but it unable to fetch the Names and show it in a AutoComplete manner.
NewUser.php
<?php
$db = pg_connect("host=hostname port=5432 dbname=dbname user=vnaem password=root");
pg_select($db, 'post_log', $_POST);
$query=pg_query("SELECT id,name FROM users_users");
$json=array();
while ($student = pg_fetch_array($query)) {
$json[$student["id"]] = $student["name"];
}
$textval = json_encode($json);
$foo = "var partnames=" . $textval;
file_put_contents('autocomplete-Files/NewEntryValues.js', $foo);
?>
. . . . . . . .
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Name: </label>
<div class="col-md-4 col-sm-2 col-2">
<input id="partner_names[]" name="partner_names[]" type="text" placeholder="Enter Full Name" class="form-control input-md newentry" style="width: 100%;">
</div>
<script type="text/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 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 increme
$(wrapper).prepend('<br><div style="margin-left:50px;"><center><div class="form-group"> <label class=" control-label" for="textinput" style="margin-left:327px;">Name: </label> <div > <input id="partner_names[]" name="partner_names[]" type="text" placeholder="Enter Full Name" class="form-control input-md newentry" style="margin-top: -25px;margin-left: 403px;width: 241%;"> </div> <img src="images/del24.png" style="margin-left: 810px; margin-top: -81px;"></a></div>'); //add input box\
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
. . . . . . . .
<script type="text/javascript" src="NewEntryValues.js"></script>
<script type="text/javascript" src="autocomplete.js"></script>
As you can see above, the class in Input Tag is newentry and in the Javascript also newentry,
I am fetch that newentry class name in a Another which takes care of Database connection and the AutoComplete Logic.
So , how can the get that logic working in this script tag too !
autocomplete.js
$(function() {
'use strict';
var peopleArray = $.map(partnames, function (value, key) {
return { value: value, data: key }; });
// Setup jQuery ajax mock:
$.mockjax({
url: '*',
responseTime: 2000,
response: function(settings) {
var query = settings.data.query,
queryLowerCase = query.toLowerCase(),
re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
suggestions = $.grep(peopleArray, function(search) {
// return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
return re.test(search.value);
}),
response = {
query: query,
suggestions: suggestions
};
this.responseText = JSON.stringify(response);
}
});
// Initialize autocomplete with custom appendTo:
$('.newentry').autocomplete({
lookup: peopleArray
});
});
NewEntryValues.js
var partnames={"19":"ABCD","42":"group","103":"cv","104":"name_to_1","105":"livetest","106":"live2"}
I am using this jQuery-Autocomplete for reference
You are initializing autocomplete on .newentry while your .newentry is not part of the DOM yet
// Initialize autocomplete with custom appendTo:
$('.newentry').autocomplete({
lookup: peopleArray
});
.newentry comes into the picture in $(add_button).click() when you prepend() the .newentry in wrapper.
Initialize your autocomplete after adding .newentry in wrapper.
Updated
In NewUser.php,
$(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 peopleArray = $.map(partnames, function (value, key) {
return { value: value, data: key };
});
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 increme
$(wrapper).prepend('<br><div style="margin-left:50px;"><center><div class="form-group"> <label class=" control-label" for="textinput" style="margin-left:327px;">Name: </label> <div > <input id="partner_names[]" name="partner_names[]" type="text" placeholder="Enter Full Name" class="form-control input-md newentry" style="margin-top: -25px;margin-left: 403px;width: 241%;"> </div> <img src="images/del24.png" style="margin-left: 810px; margin-top: -81px;"></a></div>'); //add input box
//Initialize autocomplete here when it has become the part of the DOM
$('.newentry').autocomplete({
lookup: peopleArray
});
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
You need to initialize text input after it has been appended to DOM.When you use .newentry as selector it gets elements that are part of DOM currently, but not the elements that will be appended later.
Try something like this. Carefully go through the code. It is a part of my previous code and it works wonderfully. I have got the values in text box but as you can see in my php code i have commented the code to get the values in a drop-down.
Your php file (autocomplete.php)
<?php
$searchTerm = $_GET['term'];
$query = mysql_query("select name from test where name LIKE '%".$searchTerm."%' ORDER BY name ASC"); // Run your query
/*echo '<select name="taskname">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';*/
while ($row = mysql_fetch_array($query)) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
?>
Your HTML File:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function()
{
$( "#skills" ).autocomplete({
source: 'autocomplete.php'
});
});
</script>
<td><input id="skills" name="taskname"></td></tr>
<label for="skills">Task Name: </label>
<input id="skills">
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();