Fields Added Via Javascript not posting Data into $POST - javascript

I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">

You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];

FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.

Related

How do i clear multiple user inputs in javascript

I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything.
i want to make the reset button to clear user inputs?
Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong.
Please i'll appreciate if anyone can assist me with this.
<div class=" DTRloading__form" style="display: block;">
<div class="form-container">
<div class="info">
</div>
<form class="form-inline">
<div class="form-group w-5 ">
<label for="red">Red Phase:</label>
<input type="number" class="form-control formInline" id="red" style="width: 80px">
</div>
<div class="form-group">
<label for="yellow">Yellow Phase:</label>
<input type="number" class="form-control formInline" id="yellow" style="width: 80px">
</div>
<div class="form-group">
<label for="blue">Blue Phase:</label>
<input type="number" class="form-control formInline" id="blue" style="width: 80px">
</div>
<div class="form-group">
<label for="neutral">Neutral:</label>
<input type="number" class="form-control formInline" id="neutral" style="width: 80px">
</div>
</form>
<label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label>
<input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required>
<button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button>
</div>
<div class="output">
<h5 class="b-display">DTR Full Load Current is:</h5>
<div id="flA" class="form-control bill"></div>
<h5 class="b-display">The percentage Loading of this DTR is:</h5>
<div id="outputLoading" class="form-control bill"></div>
<!-- <div id="outputSum" class="form-control bill"></div>-->
<button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button>
</div>
</div>
<script>
document.getElementById("btnStart3").addEventListener('click', doCalc);
function doCalc() {
// Assign user inputs to variables
let x = parseFloat(document.querySelector("#red").value);
let y = parseFloat(document.querySelector("#yellow").value);
let z = parseFloat(document.querySelector("#blue").value);
let n = parseFloat(document.querySelector("#neutral").value);
const capacity = document.querySelector("#inputKVA");
const output2 = document.querySelector("#outputLoading");
const output3 = document.querySelector("#flA");
const start3 = document.getElementById("btnStart3");
const refresh3 = document.getElementById("btnRefresh3");
// // Call the average function
getAverage(x,y,z,n);
}
function getAverage(x,y,z,n) {
// Calculate the average
let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100);
// Display result to user
console.log(average);
outputLoading.innerHTML = average.toFixed(0) + "%";
//
}
const capacity = document.querySelector("#inputKVA");
function calculate(e) {
console.log(e);
e.preventDefault();
console.log("btnStart3 clicked");
var totalfLA = ((capacity.value * 1000) / (1.7321 * 415));
console.log(totalfLA);
flA.innerHTML = totalfLA.toFixed(1) + "A";
}
function emptyInput() {
console.log("emptied!");
outputKVA.innerHTML = "";
flA.innerHTML = "";
x.value = "";
y.value = "";
z.value = "";
n.value = "";
capacity.value = "";
output2.value = "";
output3.value = "";
}
btnStart3.addEventListener("click", calculate);
refresh3.addEventListener("click", emptyInput);
</script>
You can try in html with below button type as well.
<input type="reset" value="Reset">
If you want reset form from javascript then
document.getElementById("your-form-id").reset();
Change
1. <form class="form-inline">
2. refresh3.addEventListener("click", emptyInput);
to
1. <form class="form-inline" id="form">
2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput);
3. function emptyInput() {
document.getElementById("form").reset();
}

Connect clicked button value and function in JS

I'm beginner in JS.
I have 2 functions. How to do :
if I click first button, make first function work, if I click second button, make second function work?
Apply pressed button value to function and then apply it to input field.
Example: when I type 'ABC' using Caesar Cipher , it would return 'NOP', when I type 'ABC' using my cipher (or any other), it would return 'BCD' (or any other value, it depends on which cipher is selected). Thanks everyone in advance
My Js and Html code below:
<div class="container">
<div class="row">
<form class="col s12 m12 l12">
<h2>JS Encription</h2>
<div class="row">
<div class="input-field col s5 m5 l5">
<input id="field1" placeholder="Type you text here" id="first_name" type="text" class="validate">
<label for="first_name">Input</label>
</div>
<div class="input-field col s5 m5 l5">
<input id="field2" disabled placeholder="Result is shown here" id="first_name" type="text" class="validate">
<label for="first_name">Output</label>
</div>
</div>
</form>
</div>
<div class="row switchBtns">
<div class="col s12 m12 l12">
<div id="caesarButton" class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">Caesar Cipher</a>
</div>
<div id="mineButton" class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">My Cipher</a>
</div>
<div class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">3rd Variant</a>
</div>
<div class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">4th Variant</a>
</div>
</div>
</div>
</div>
and JS code
// CAESAR
$("#caesarButton").click(function() {
var clicked = $(this).val();
$('#field1').val(encryp(clicked)).val();
});
$('#field1').on('keyup keypress blur', function () {
var textvalue = $(this).val();
$('#field2').val(encryp(textvalue)).val();
});
function encryp(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+13);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-13);
}
else {
result+=" ";
}
}
return result ;
}
//MINE
$("#mineButton").click(function() {
var clicked = $(this).val();
$('#field1').val(encryp(clicked)).val();
});
$('#field1').on('keyup keypress blur', function () {
var textvalue = $(this).val();
$('#field2').val(encryp(textvalue)).val();
});
function encryp(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+3);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-3);
}
else {
result+=" ";
}
}
return result ;
}
I whipped up a simplified example of contextually switching input handler functions for you, here ya go:
// use an object as a key-value store for your functions
var funcs = {
caesar: encryp1, // i dont know if i got these the right way around :D
mine: encryp2
}
// store which funciton is currently selected in a variable
var selected = "caesar"
// call this function just to show the default selected function
determineOutput()
// CAESAR
$("#caesarButton").click(function() {
console.log("caesar button clicked!")
// here assign which function to use
selected = "caesar"
determineOutput()
});
//MINE
$("#mineButton").click(function() {
console.log("mine button clicked!")
// here assign which function to use
selected = "mine"
determineOutput()
});
$('#field1').on('keyup keypress blur', function () {
// this function is alled every time one of the events
// listed happens on the #field1 element
determineOutput()
});
function determineOutput(){
var textvalue = $('#field1').val();
//use the function currently selected by addressing it with
// [] on the funcs object
var correctFunction = funcs[selected]
// then call the selected function with the input text
$('#field2').val(correctFunction(textvalue));
// show the user which cipher we're using
$("#currentCipher").html("current cipher:" + selected)
}
function encryp1(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+13);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-13);
}
else {
result+=" ";
}
}
return result ;
}
function encryp2(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+3);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-3);
}
else {
result+=" ";
}
}
return result ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="field1" placeholder="Type you text here" type="text">
<label for="field1">Input</label>
</div>
<div>
<input id="field2" disabled placeholder="Result is shown here" type="text" class="validate">
<label for="field2">Output</label>
</div>
<p id="currentCipher"></p>
<button id="caesarButton">
Caesar Cipher
</button>
<button id="mineButton">
My Cipher
</button>

Array of html inputs

I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/

create textboxes and Insert data at page loading

I would like to know how can I create textboxes and insert data at page load.
What I'm trying to do is open an array string from a database, create the textboxes and populate the textboxes at page load.
I have an array string from an ms sql database that looks something like this
test,test;bla;bla2;test44;test55;test66
I separated each individual array with ; and I would like to create textboxes and insert the values into a textbox, one-by-one, so the end result would look like this:
I don't know how to do it using the code below.
Whatever I try I mess up the add/remove functions or I end up cloning all textboxes when the plus button is clicked.
THANKS
SEE CODE BELOW OR GO TO https://jsfiddle.net/kj3cwww0
<script type='text/javascript'>//<![CDATA[
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('#template_add_form'),
formArray = [ clone($template) ], // init array with first row
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
updateForm(); // first init. of form
});
//]]>
</script>
<script id="template_add_form" type="text/template">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</script>
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
FORM SUBMIT CODE:
<body>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
......the rest of the existing code goes here...
</div>
</form>
</body>
CALLING IT VIA CLASSIC ASP:
if strComp(Request.Form("action"), "submit")= 0 then
Response.write("IT WORKS")
end if
Here is a solution that works :
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
formArray = [ ], // init array enpty
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
$('#template_add_form').remove();
});
.entry:not(:first-of-type)
{
margin-top: 10px;
}
.glyphicon
{
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
<div id="template_add_form" type="text/template" style="display: none;">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</div>
</form>
</body>
Here's what I changed to your code :
Changed the template which was a <script> to a <div>, and hid it by default using style="display: none;" :
<div id="template_add_form" type="text/template" style="display: none;">
Initialized array empty, so that we can put our own first line : formArray = [ ],
Created a function to add a string in the form :
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
At the end, I added some example data, then pushed an empty line and updated the form :
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
EDIT : I also deleted the template div at the end so that it isn't taken into the form when you submit :
$('#template_add_form').remove();
To be able to do that, I cloned it entirely at start :
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),

How do you add functions to an assortment of buttons sequentially

I have several div tags with the class of opt that have an input and button element inside them. I am trying to create a function that will take the value from the input tag and when you click the button, the next input and button field will pop up and ask you to enter different information, while the previous input and button tags will hide itself. However, the function is not working here is the jsfiddle.
HTML
<div id="container">
<div class="opt active"> <input type="text" placeholder ="Enter Name"name="name"> <button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder ="Enter Age" name="age"> <button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder ="Enter Race" name="race"> <button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder ="Enter Sex" name="sex"> <button id="done">Done</button>
</div>
</div>
Javascript
function init(){
var opt = document.getElementsByClassName('opt');
var num = 0;
var prop = [];
var propVal = [];
for (var i = 0 ; i < opt.length; i++)
{
opt[i].querySelector('input').value = "";
}
opt[num].querySelector('button').onclick = function()
{
prop[num] = opt[num].querySelector('input').name;
propVal[num]= opt[num].querySelector('input').value;
opt[num].className = "opt";
opt[num+1].className ="opt active";
console.log(prop +" "+ propVal);
num++;
};//button function
}
init();
You need bind the click handlers in the loop as well. You also don't need to use parallel arrays to store the properties when you could use an object instead.
Make sure that there is a "next input" before trying to change the class of the next one.
var opt = document.getElementsByClassName('opt'),
num = 0, prop = {};
function nextInput() {
var input = opt[num].querySelector('input');
prop[input.name] = input.value;
console.log(prop);
opt[num].className = "opt";
if (num + 1 < opt.length) {
opt[num + 1].className = "opt active";
num++;
} else {
// submit?
}
}
for (var i = 0; i < opt.length; i++) {
opt[i].querySelector('input').value = "";
opt[i].querySelector('button').onclick = nextInput;
}
.opt { display: none }
.opt.active { display: block }
<div id="container">
<div class="opt active">
<input type="text" placeholder="Enter Name" name="name">
<button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder="Enter Age" name="age">
<button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder="Enter Race" name="race">
<button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder="Enter Sex" name="sex">
<button id="done">Done</button>
</div>
</div>

Categories