i wanted to know how to compute the sum of all fields that are dynamically added and display the result in the page but i got lost in the way.
here is the code i am trying to review and learn:
thank you in advance ^__^
i need to know what to do next so i can add it to this one.
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="field_wrapper">
<div class="form-group">
<input type="text" class="prc" name="field_name[]" value=""/>
add field
</div>
</div>
<div class="form-group">
<output id="result"></output>
</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 = '<div><input type="text" name="field_name[]" value=""/>remove field</div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
</body>
</html>
any help is very much appreciated. thank you so much!
Assuming input number is integer:
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
calculate_sum();
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
calculate_sum();
});
function calculate_sum() {
let sum = 0;
$('.field_wrapper').find('input.prc').each((index, element) => {
sum += parseInt(element.value);
});
$('#result').text(sum);
}
Don't forget to add class prc to input in variable fieldHTML.
I also would suggest you to change input type="text" to input type="number"
Related
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();
});
I have a Laravel form that collects info from a user. On one part of the form I want to add a button that will add a row containing 4 text boxes (each named differently) that the user can fill in. Each time the user clicks the button, another row of 4 text boxes should be added.
In an ideal world, the code will be a javascript function (so I can reuse it later) called by a button click. I can't seem to see how to add an event handler to a button click on a laravel form.
This works
HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
JS
$(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
$("#rm").remove();
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/>'); //add input box
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/>'); //add input box
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/></div>'); //add input box
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/>Remove</div>'); //add input box
$(wrapper).append('<br>')
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $("#divs").remove(); x--;
$("#divs").remove(); x--;
$("#divs").remove(); x--;
$("#divs").remove(); x--;
})
});
the name will be mytext (first input name = mytest[1] second mytest[2] ...etc)
you can add the X variable to the form so you know how many input you have in your controller
in the html , you can change the type to hidden so you want have any input fields untill user click
check result this in JSFiddle
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 have a form that you can add fields: http://jsfiddle.net/ytrkqr6a/2/
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //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 class="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control cameras" readonly /> Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>
<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control cameras" readonly /></div>
</div>
Everything works fine adding fields, but where I'm hung up is when you remove one of the fields then numerical order gets off.. how do I make it update the remaining fields to stay in proper numerical order each time you add or remove a field:
Camera 1
Camera 2
Camera 3
etc...
Thanks ahead of time!
I just added a jQuery "each" loop to re placerholder, name, and value each input field every time a remove link is clicked. When using each the value passed to the function is the index of item in the loop's current iteration, I used the variable elm. Since each input field is classed with camerasCounter, you can use $(this) to easily call the input element in the loop. Each is a very useful part of jQuery, if you ask me.
http://jsfiddle.net/v76zn30o/2/
The HTML
<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>
<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control camerasCounter" readonly /></div>
</div>
and The jQuery
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //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 class="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control camerasCounter" readonly /> Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
$(".camerasCounter").each(function(elm){
x = elm + 1
$(this).attr({
"placeholder": "Camera " + x,
"name": "Camera " + x,
"value": "Camera " + x
});
});
});
});