How do I organize DOM HTML elements - javascript

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>

Related

Read data from Javascript dynamic input in node.js

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>

Add/Remove multiple inputs type text using jQuery

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.

Adding dynamic input based on one field that contains a sum of two other inputs

I am working on a form that sums two inputs and put the result of this sum in another input.
Input #1 is type number and it's called adult_qty
Input #2 is type number and it's called kid_pay_qty
The input that receives the sum is called qty_traveling.
This is the HTML
<form>
....
<label for "adult_qty">How many adults:</label><br/>
<input type="number" name="adult_qty" id="adult_qty" size="5" value="0">
<label for "kid_pay_qty">How many children:</label><br/>
<input type="number" name="kid_pay_qty" id="kid_pay_qty" size="5" value="0">
<label for "qty_traveling">Total of Pax:</label><br/>
<input type="text" name="qty_traveling" id="qty_traveling" size="5" value="0" readonly>
<p><h2>Other Pax Information</h2></p>
<div class="input_fields_wrap">
</div>
....
</form>
Then I have a JQuery that will calculate the two inputs and attribute the result to the third input. So far it is working very good.
Finally I am trying to add to this form dynamic inputs called First Name and Last Name inside of a div called input_field_wrap in the same amount displayed on the sum of the two inputs.
Let's say that the result is two, I would like to have two First Name and two Last Name inputs added to the form dynamically. Whatever is the result, I would like to have this amount added dynamically as soon as the sum is given to the "qty_traveling" input.
Please see below my JQuery script:
$(document).ready(function() {
$('#adult_qty').keyup(function() {
updateTotal();
});
$('#kid_pay_qty').keyup(function() {
updateTotal();
});
});
function updateTotal() {
var input1 = parseInt($('#adult_qty').val());
var input2 = parseInt($('#kid_pay_qty').val());
var total = input1 + input2;
$('#qty_traveling').val(total);
var max_fields = total; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var x = 1; //initlal text box count
while(x < max_fields){
e.preventDefault();
x++; //text box increment
$(wrapper).append('<div><div id="left_col"><label for "otherFirstname[]">First Name:</label></div><div id="right_col"><input type="text" name="otherFirstname[]" id="otherFirstname"/></div></div>'); //add input box
$(wrapper).append('<div><div id="left_col"><label for "otherLastname[]">Last Name:</label></div><div id="right_col"><input type="text" name="otherLastname[]" id="otherLastname"/></div></div>'); //add input box
}
};
};
The sum is working perfectly and it gets updated as the Keyup determines but the inputs are not being added to the form.
Thanks in advance for any help.
First, e.preventDefault() is breaking your code. And you need to change you condition in the while loop. Since 2 < 2 is always false in you 2nd or last loop if your total is 2.
Make sure you empty wrapper's content before you append the inputs. You can use jQuery empty() to your code.
Working Demo.
Change your function:
function updateTotal() {
var input1 = parseInt($("#adult_qty").val());
var input2 = parseInt($("#kid_pay_qty").val());
var total = input1 + input2;
$("#qty_traveling").val(total);
var max_fields = total; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var x = 1; //initlal text box count
$(wrapper).empty();
while (x <= max_fields) {
//e.preventDefault();
x++;
//text box increment
$(wrapper).append(
'<div><div id="left_col"><label for "otherFirstname[]">First Name:</label></div><div id="right_col"><input type="text" name="otherFirstname[]" id="otherFirstname"/></div></div>'
); //add input box
$(wrapper).append(
'<div><div id="left_col"><label for "otherLastname[]">Last Name:</label></div><div id="right_col"><input type="text" name="otherLastname[]" id="otherLastname"/></div></div>'
); //add input box
}
}
Also, make sure you ids are unique.

How to Grab input values of dynamically added input boxes using jquery

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();

Webmatrix: Add items to dynamic dropdown box from DB with jquery

So i got a button to add more dropdown boxs done with jquery, here's the function that will create the new boxes
$(document).ready(function() {
var MaxSelects = 7; //maximum input boxes allowed
var SelectsWrapper = $("#SelectsWrapper"); //Input boxes wrapper ID
var AdicionarButton = $("#AdicionarFileBox"); //Add button ID
var x = SelectsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AdicionarButton).click(function (e) //on add input button click
{
if(x <= MaxSelects) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(SelectsWrapper).append('<div class="selectAplic"><select name="aplicacaoPretendida" id="aplicacoes" class="col_11"></select><a class="removeclass" href="#"><i class="icon-remove"></i></a></div>');
x++; //text box increment
}
return false;
});
However when i put my foreach inside nothing happens, The box is created but the content is empty.
#foreach(var row in selectedData){
foreach(var item in row.aplicacoes.ToString().Split(new [] {','})){
<option>#item</option>
}
}
This is my code working:
<div id="SelectsWrapper" class="col_8">
<div class="selectAplic">
<select name="aplicacaoPretendida" id="aplicacoes" class="col_11" onchange='userExemplo()'>
#foreach(var row in selectedData){
foreach(var item in row.aplicacoes.ToString().Split(new [] {','})){
<option>#item</option>
}
}
</select>
</div>
</div>
Now how can i add the foreach at mt jquery ?

Categories

Resources