Javascript - Remove an element from dynamic form - javascript

I'm currently working on a form that has a "+' button that allows to display dynamically the same form again.
This part is working fine, I got a problem when adding the delete button that allow to remove a part of the form. It deletes everytime the whole dynamically generated form instead of just the "clicked" form that corresponds to the counter of the dynamic form.
Here is my html code
<!-- Div that the content the dynamic form -->
<div id="dynamicInput">
</div>
<!-- Input button that active the script onClick -->
<input type="button" class="add_delivery" value="Ajouter une destination" onClick="addInput('dynamicInput');">
Here is my javascript
var counter = 1; // Count the number of dynamic form generated
var limit = 20; // Limit amount of dynamic form
// Function to add the form
function addInput(divName){
// Check if max limit is reached and display alert
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
// If limit max is not reached create the form element
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='delivery_booking_container_left_recipient'><a href='javascript:void(newdiv);' class='remove'>×</a><div class='recipient_name_title2'>Destinataire " + (counter + 1) + "</div><input type='text' name='recipient_name' id='recipient_name' class='delivery_field_recipient_name' placeholder=' Destinataire' value='<?php if(isset($recipient_name)) { echo $recipient_name; } ?>'><input type='text' name='recipient_phone' id='recipient_phone' class='delivery_field_recipient_phone' placeholder=' N° de téléphone' value='<?php if(isset($recipient_phone)) { echo $recipient_phone; } ?>'/></div><div id='ocationField2'><input id='autocomplete2' name='recipient_address' class='delivery_field_recipient_address' placeholder=' Adresse' onFocus='geolocate()'' type='text' value='<?php if(isset($recipient_address)) { echo $recipient_address; } ?>'/></div><div id='addresstwo'><input type='text' id='street_number2' name='street_number2' /><input type='text' id='route2' name='street_name2' /><input type='text' id='locality2' name='town_city2' /><input type='text' id='administrative_area_level_12' name='administrative_area_level_12' /><input type='text' id='postal_code2' name='postcode2' /><input type='text' id='country2' name='country2' /></div><textarea name='recipient_more_infos' id='recipient_more_infos' class='delivery_field_sender_more_infos' placeholder=' Informations complémentaires' value='<?php if(isset($recipient_more_infos)) { echo $recipient_more_infos; } ?>'></textarea>";
// Function to remove a dynamic form on click using the <a href='javascript:void(newdiv);' class='remove'>×</a>
$(document).on("click", "a.remove" , function() {
document.getElementById(divName).appendChild(newdiv).remove(newdiv);
// Reset the input to have the right count when adding a new on after deleting
resetaddInput(newdiv);
});
// Add ++ to the counter
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}

You need to add some parent div/p element to use as selector that can select whole newly added form like
<div class="fomesection">
<div class='delivery_booking_container_left_recipient'><a href='javascript:;' class='remove'>×</a>....</textarea>
</div>
now whenever you click on button remove remove the parent div it will work fine..; or if you are using jQuery to remove it can possible easily using code is :
jQuery(document).on('click','.remove',function(){
jQuery(this).parents('.fomesection').remove();
});

Related

Adding new input fields on check box ticked

I have a table with 3 text fields
i want to add the same text fields on clicking check box i have the following code
how can i do it with php and javascript
echo "<td>Screen ".$i."</td>";
echo "<td><input type='text' id='filmname".$k."' name='filmname".$k."'value='".$prefilm."'></td>";
echo "<td><input type='text' id='Language".$k."' name='Language".$k."'value='".$prelang."'></td>";
echo "<td><input type='text' id='showtime".$k."' name='showtime".$k."'value='".$prescreen."'></td>";
echo "<td ><input type='checkbox' class='Checkbox' id='addshow".$k."' autocomplete='off'
name='addshow".$k."' value='addshow' onclick='addshow(".$k.")</td>";
It would be great if you can clarify where you want to add which text fields when the checkbox got checked.
Two ideas:
You can create your text fields at the same time when you create your table and then hide/show them with CSS and JavaScript. (Preferred)
Add a click listener to your checkbox and create your text fields dynamically with JS with document.createElement('input') Learn more here
Code examaple for the 2nd option:
const check = document.querySelector('input[type=checkbox]');
check.addEventListener('click', createTextInput);
function createTextInput() {
const target = document.querySelector(YOUR TARGET SELECTOR);
const input = document.createElement('input');
input.setAttribute('type', 'text');
input.addEventListener(OPTIONAL IF YOU WANT)
target.appendChild(input); // this adds the new input into your target
}

How to display mysql data through javascript in dynamic form field

I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>

Javascript function for form created using Javascript

I have a script which adds a new form when a button is clicked to a HTML page with the code as following:
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("Max number of forms, " + counter );
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<form name='frmMain' action='prelucrare.php' method='POST'><div class='slot' id='dynamicInput' align='center'> Masina " + (counter +1 ) + "<table border='1'><tr><td align='right'><label for='marca'>Marca:</label></td><td colspan='2' align='left'>"
+ "<select id='marc' name='marc'><option selected value=''></option>"
+ "<tr><td align='right'><label for='motorizare1'> Motorizare:</label></td> <td><input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id=motor1 oninput='outputUpdate1(value)'></td><td><output for=motorizare1 id=moto1>2</output></td></tr>"
+ "</div></form>"
;
}
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
<input type="button" value="Adauga" onClick="addInput('dynamicInput');">
And I have the script bellow which changes the value from the slider.
<script>
function outputUpdate1(mot1) {
document.querySelector('#moto1').innerHTML = mot1;
}
</script>
My problem is that the JS code only changes the input for the first form, even if the slider is activated from another form. In short, the slider should return the value in the form from which it is activate; not only in the first form added.
Thank you!
Going along with my comment, the problem is stemming from the id value being the same across all of your output elements (moto1). You've actually got all the variables you need to make them unique since you're tracking a count of the number of forms on the page (your counter variable). You can use this in place of your current output HTML:
"<input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id='motor_" + counter + "' oninput='outputUpdate1(value)'/>"
"<output for=motorizare1 id='moto_" + counter + "'>"
You can update your function to parse out the correct index for the output you want to update since they should be in sync if you use the HTML above:
function outputUpdate1(mot) {
// Get the counter part of the range element's id
var index = mot.id.split('_')[1];
document.querySelector('#moto_' + index).innerHTML = mot;
}
You may need to make some tweaks to code you haven't provided in the question, but that's one way of making the id values unique and how to access them without knowing the exact id ahead of time.

Create and Insert an Input on "Enter"

I am trying to create and insert an input(b) below another input(a) on "Enter" of input(a), while also inserting the value of input(a) into input(b).
Javascript
function add_name(ele) {
if(event.keyCode == 13) {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input id='person_holder' type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
var personName = document.getElementById("people").value;
document.getElementById('person_holder').value= personName;
}
}
HTML
<form>
<input type="text" class="add_name" onkeydown="add_name(this)" name="myInputs[]" id="people"/>
</form>
If this is your complete code, then I think the problem results from the default behavior of input text box in form. For a input text box in form, when it's focused and enter button is pressed, the form will be submitted, meaning the page will be reloaded. To prevent this, you can add event.preventDefault();. Here's the working demo.

php won't post value to email

I have added a button onclick function to a web form, so that onClick new input text field is created. However when the forms posts to email, Quote_Num value isn't posted - it just says "Array"
JS
var counter = 1;
var limit = 8;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Quote Number " + (counter + 1) + " <p><input type='text' name='Quote_Num[]' /></p>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
HTML
<div id="dynamicInput">
Quote Number
<p><input type="text" id="Quote_Num" name="Quote_Num[]" class="required" /> *</p>
</div>
<p><button type="button" value="Add another text input" onClick="addInput('dynamicInput');">Add Quote Number</button></p>
PHP
<?php
$Quote_Num = $_POST["Quote_Num"];
foreach ($Quote_Num as $eachInput)
{
echo $eachInput . "<br>";
}
?>
Anyone with my experience with PHP help me get the form to post value of Quote_Num?
The variable $Quote_Num set with $Quote_Num = $_POST["Quote_Num"]; is an array, as you are submitting more then one values values from your HTML form by setting name equal to Quote_Num[].
If you echo an Array in PHP, It will give an Notice, and print 'Array'.
If you want all of the values of the array $Quote_Num you can use implode on Array. For example implode(", ", $Quote_Num) will return comma separated list of all values in the array as String.
You may also print the whole array by using var_dump or print_r.
I hope, I got your question and it helps.

Categories