I am using javascript to add and delete input fields. Fields are properly added, data is saved and displayed too. But when I click remove button in the field that is generated from database, it is not removed. It takes me to the top of the page. But if I click add more fields, new field is generated through javascript and it is removed when I click its remove. Where am I wrong?
HTML AND JAVASCRIPT
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
</div>
<?php
// retrieve the user meta
$fb = get_user_meta($user->ID, 'business_sm_fb', false);
if (!empty($fb)) {
?>
<?php foreach ($fb as $f_b) {
?>
<?php foreach ($f_b as $val) { ?>
<div><input type="text" name="sm_fb[]" type="text" class="regular-text" value="<?php echo $val; ?>" />Remove</div>
<?php
}
}
?>
<?php } else {
?>
<div><input type="text" name="sm_fb[]" type="text" class="regular-text" /></div>
<?php } ?>
<script>
$(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><input type="text" name="sm_fb[]" type="text" class="regular-text" />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>
the issue seems to be related to the wrapper object:
var wrapper = $(".input_fields_wrap");
In your script you bind the click event to all the .remove_field items, that are inside the wrapper object:
$(wrapper).on("click", ".remove_field", function (e) {
....
})
The problem is that the .remove_field items are added via PHP on the outside of the .input_fields_wrap div, therefore the click event does not work.
As you can see here, the .input_fields_wrap is opened and immediately closed after the <button />. Your PHP code adds the inputs outside this div.
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
</div>
To solve the issue, move the closing div tag after the PHP code block.
Related
I'm trying to get the value from dynamic drop-down list in my form, but my code isn't working.
View.php
<div class="input_fields_wrap">
<input type="button" class="btn btn-info add_field_button" value="Tambah Cara Pengolahan" /> <br /><br />
</div>
<div class="service-container" data-service=
"<div class='form-group'>
<select class='form-control' style='width:88%; display:inline-block; margin-right:10px;' name='cara_pengolahan[]' required>
<option value=''>No Selected</option>
<?php foreach($pengolahan as $row):?>
<option value='<?php echo $row->id_pengolahan;?>'><?php echo $row->cara_pengolahan;?></option>
<?php endforeach;?>></div>
</select>
<button class='btn btn-danger closebtn remove_field'><b>×</b></button>
</div>"
</div>
Javascript.js
$('.service-container').each(function() {
var container = $(this);
var service = container.data('service');
// Service variable now contains the value of html + php variable;
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(service);
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
var cara_pengolahan = document.forms[0].elements["cara_pengolahan[]"];
if(typeof cara_pengolahan !== 'undefined'){
for (var i=0; i<cara_pengolahan.length; i++) {
console.log(cara_pengolahan[i].value);
}
}
When there is one dynamic drop-down list, it returns all the array values of it. But what I want is to capture the selected value of that drop-down list.
And when there are more than one dynamic drop-down lists, it returns the correct selected values of that drop-down lists.
How to capture the selected value of all the dynamic drop-down lists?
Thanks in advance.
Try this:
myval= $("#id").find("option:selected").val();
Where #id is the id of your select input
To check if there is a dynamic Drop down you can simple check if the selector exists
with
$('#elemId').length>0
And for selected value you can use $("#selectorid").find("option:selected").val();
I have a simple text input using the timepicki jquery plugin. I am able successfully use the plugin on my first text input, but I am not able to use it on the additional inputs created by array as shown.
<script>
$(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
$('#timepicker').timepicki(); //Call Timepicki plugin for #timepicker ID
$(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="timepicker[]"/>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>
<html>
Ring Time:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" id='timepicker' type='text'name='timepicker[]'"></div>
</div><br><br>
</html>
My question is - How can can enable it so that all instances of the timepicker input can use the timepicker plugin?
Thanks!
Theres a couple of changes that should make it work
$('.timepicker').timepicki(); //class instead of id
and in your HTML and javascript
<input type="text" class="timepicker" name="timepicker[]" />
in the click function
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" class="timepicker" name="timepicker[]"/>Remove</div>');
}
$('.timepicker').timepicki();
});
Need to add textbox and textarea dynamically to one of my forms. I found this example which works fine for adding textbox dynamically.
Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<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 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--;
})
});
</script>
HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Result
I tried adding a textarea
$(wrapper).append('<div><textarea name="desc[]"></textarea></div>Remove</div>');
to the above javascript
and to the HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
<div><textarea name="desc[]"></textarea></div>
</div>
but it turns out to be erroneous. How should I add a textarea along with the textbox?
Error
The maximum limit allowed is 10. Say I add 6 of these fields and then decide to use 5 of them. If, I remove the last (6th one in this case) all of them get removed.
EDIT
Link to the above code https://jsfiddle.net/x6krv00u/
** I do not know much about javascripts.**
I think you are doing like this
$(wrapper).append('<div><input type="text" name="mytext[]"/><textarea name="desc[]"></textarea></div>Remove</div>');
And for this following should work
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
$(this).parent().remove(); // you cannot pass 'div' in parent()
});
The input and textarea don't have the same parent. That's what's causing the problem.
This should be the DOM structure:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="mytext[]"><br>
<textarea name="desc[]"></textarea>
</div>
</div>
Of course, the <br> is optional. You should probably use CSS for formatting instead.
Here's how you add an input-textarea pair:
$(wrapper).append('<div>' +
'<input name="mytext[]"><br>' +
'<textarea name="desc[]"></textarea>' +
'Remove' +
'</div>');
Here's a working example, which you can copy-paste:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="mytext[]"><br>
<textarea name="desc[]"></textarea>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<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 increment
$(wrapper).append('<div>' +
'<input name="mytext[]"><br>' +
'<textarea name="desc[]"></textarea>' +
'Remove' +
'</div>');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Hope this helps.
PS: I've tried to make minimal changes to your code. There are other (better) ways of accomplishing what you want.
Edit 0: Improved formatting.
I have 2 form component that i would like to add dynamically (allow user to add more than 1)
First i have a dropdownlist with values populated from MySQL. Followed by a text box which allows user to enter some enquires.
Basically, the dropdownlist will show a list of user and a textbox for the person to type a message to the person.
The user is allow to send to multiple different user, therefore there is a ADD button which will add another dropdownlist and a text box..
I tried using jQuery append. but append does not accepts PHP as its server side.
I also tried to jQuery clone to clone the whole DIV but fails.
I am using this code to add field dynamically
Add Remove field dynamically
This is my code for the dropdownlist and textbox
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<select name="msgrecever1" style="background:#252525" >
<option value="">Select Faculty</option>
<?php
require_once("../dbconnection/dbcon.php");
$sql="SELECT * FROM user WHERE role='Faculty'";
$records=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($records)){
$name=$row['username'];
echo "<option value='$name'>".$name."</option>";
}
?>
</select><input type="text" name="mytext[]"></div>
I want to duplicate as many of the above code as long as the user press "add new field"
jQuery:
$(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
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=\"mytext[]\"/>Remove');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
=================
EDITED:
i have used this solution and it works.
<?php require_once("../dbconnection/dbcon.php");
if(isset($_POST['submit']))
{
$capture_field_vals ="";
foreach($_POST["msgrecipient"] as $key => $text_field)
{
echo "Key: $key; Value: $text_field<br />\n";
echo "<br>";
}
foreach($_POST["enquiry"] as $key => $text_field2)
{
echo "Key: $key; Value: $text_field2<br />\n";
echo "<br>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // the numeric ID of the new input field being added
newElem = $('#testingDiv' + num).clone().attr('id', 'testingDiv' + newNum).fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
newElem.find('.test-select').attr('id', 'ID' + newNum + '_select').attr('name', 'ID' + newNum + '_select').val('');
newElem.find('.test-textarea').val('');
// insert the new element after the last "duplicatable" input field
$('#testingDiv' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled', false);
// right now you can only add 5 sections. change '5' below to the max number of times the form can be duplicated
if (newNum == 5) $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit");
});
$('#btnDel').click(function () {
// confirmation
if (confirm("Are you sure you wish to remove this section of the form? Any information it contains will be lost!")) {
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#testingDiv' + num).slideUp('slow', function () {
$(this).remove();
// if only one element remains, disable the "remove" button
if (num - 1 === 1) $('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "[ + ] add to this form");
});
}
return false;
// remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled', false);
});
$('#btnDel').attr('disabled', true);
});
</script>
</head>
<body>
<form action="#" method="post">
<!--
########################################## -->
<!-- START CLONED SECTION -->
<!-- ########################################## -->
<div id="testingDiv1" class="clonedInput">
<select name="msgrecipient[]" id="select">
<option value="">Select Faculty</option>
<?php
require_once("../dbconnection/dbcon.php");
$sql="SELECT * FROM user WHERE role='Faculty'";
$records=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($records)){
$name=$row['name'];
echo "<option value='$name'>".$name."</option>";
}
?>
</select>
<textarea id="textarea" name="enquiry[]" class="test-textarea"></textarea>
</div>
<!--/clonedInput-->
<!-- ########################################## -->
<!-- END CLONED SECTION -->
<!-- ########################################## -->
<!-- ADD - DELETE BUTTONS -->
<div id="add-del-buttons">
<input type="button" id="btnAdd" value="[ + ] add to this form">
<input type="button" id="btnDel" value="[ - ] remove the section above">
</div>
<!-- /ADD - DELETE BUTTONS -->
<input type="submit" name="submit"class="button button-block" value="Submit"/>
</form>
</body>
</html>
Assuming you have a markup like this:
<form id="faculty_wrapper">
<div class="faculty_row">
<select id="faculty" name="faculty[]">
<option value="faculty_one">faculty_one</option>
<option value="faculty_one">faculty_two</option>
<option value="faculty_one">faculty_three</option>
<option value="faculty_one">faculty_four</option>
</select>
<input type="text" name="message[]">
</div>
</form>
Add More <!-- Add More Rows -->
Submit <!-- Submit Button for further work -->
Javascript:
jQuery(document).ready(function($){
$("#add_more").on('click', function(e){
e.preventDefault(); // Prevent Default the event
var clone = $(".faculty_row").eq(0).clone(); // clone only first item
$("#faculty_wrapper").append(clone); // append it to our form
});
$("#submit").on('click', function(e){
e.preventDefault();
alert($("#faculty_wrapper").serialize()); // get serialize data for further work
})
})
You can check the working Jsfiddle.
I'm trying to add/remove items dynamically but I can't take the values of all the elements of the array.
Basically I have this form
<form action="" method="post">
<div class="input_fields_wrap">
<div>
<label> <span>Team name </span>
<input type="text" class="input-field" name="teams[]"> </label>
</div>
</div>
<span id="num_teams"></span> <label><span> </span>
<input type="submit" value="Add Team" class="add_field_button" name="add_field_button">
<input type="submit" name="next" value="Next" />
</label>
</form>
It just shows an input box where I'd have to insert the team name and two buttons ; one to go to the next page, and the other one to add a new text field using jquery.
Here it is the jquery script
<script type="text/javascript">
$(document).ready(function() {
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();
var max_fields = $('#n_teams').val(); //maximum input boxes allowed
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label><span>Team Name </span><input type="text" class="input-field" name="teams[]"> Delete</label></div>'); // add input box
$("#num_teams").html('Number of Teams: '+x);
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('label').remove(); x--;
$("#num_teams").html('Number of Teams: '+x);
})
});
</script>
The script above works perfectly: it adds and removes textfields.
The problem that I have now is that I can't take the values of the array 'teams[]' .
in a
if(isset($_POST['next']))
even if I try to take the values manually like
echo $_POST["teams"][0]; and
echo $_POST["teams"][1]; ect...
It just takes the first value (i.e. the one I don't add using jquery). It doesn't 'see' the jquery text fields added.
Of course my final aim is to insert 'teams[]' in a mysql table, but for now I noticed that I can't either take the values.
Where am I wrong ?
EDIT - SOLVED
It was a very stupid error I made in the html code. Actually there was a <div> before of the <form> that caused all the troubles. After a very accurate analysis , trying every single piece of code alone, I finally got that I just had to move the <form> above two <div> to make the code work.
I do apologize to everyone, silly me!
Instead of using name="teams[]" use name="teams" and on server side use:
$_POST['teams']
which should give you the comma separated list.
var wrapper = $(".input_fields_wrap").first();