Save dynamically generated input fields - javascript

I am using this code to generate dynamically ADD More input fields and then plan on using Save button to save their values in database. The challenge is that on Save button, I want to keep displaying the User Generated Input fields. However they are being refreshed on Save button clicked.
javascript:
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '">Item quantity: <input type="text" name="qty[]" size="4" value="' + frm.add_qty.value + '"> Item name: <input type="text" name="name[]" value="' + frm.add_name.value + '"> <input type="button" value="Remove" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
</script>
HTML:
<form method="post">
<div id="itemRows">Item quantity:
<input type="text" name="add_qty" size="4" />Item name:
<input type="text" name="add_name" />
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p>
<button id="_save">Save by grabbing html</button>
<br>
</p>
</form>

One approach is to define a template to add it dynamically via jQuery
Template
<script type="text/html" id="form_tpl">
<div class = "control-group" >
<label class = "control-label"for = 'emp_name' > Employer Name </label>
<div class="controls">
<input type="text" name="work_emp_name[<%= element.i %>]" class="work_emp_name"
value="" />
</div>
</div>
Button click event
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
counter += 1;
});
The main thing is to call e.preventDefault(); to prevent the page from reload.
You might want to check this working example
http://jsfiddle.net/hatemalimam/EpM7W/

along with what Hatem Alimam wrote,
have your form call an upate.php file, targeting an iframe of 1px.

Related

How can I add an incrementing id="" attribute to the following JavaScript generated HTML form?

I have managed to come up with the following JavaScript and HTML but now I am stuck. I want to be able to add an id="" attribute to the fields and have them numbered as I add more fields with the '+ Add' button.
I've been playing around with this but have not had any success yet. Could someone give me some suggestions or offer some solutions to this issue?
$(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><table width="100%"><tr><td><input type="text"
name="field_name[]" value="" class="form-control" style="width:98%;"
placeholder="Role"/></td><td><input type="text" name="field_name[]" value=""
class="form-control" style="width:100%;" placeholder="Name"/></td></tr></table>
<a href="javascript:void(0);" class="remove_button"><button type="button"
class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> -
Remove </button></a></div>';
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
});
});
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%"/>
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%"/>
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field">
<button style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role </button>
</a>
</div>
</div>
You can try this snippet:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
$(document).ready(function () {
var x = 1; //Initial field counter is 1
var idCounter = 0;
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
function fieldHTML(id) {
return '<div><table width="100%"><tr><td>id:' + id + '<input type="text"' +
'id="role-' + id + '" name = "field_name[]" value = "" class="form-control" style = "width:98%;"' +
'placeholder = "Role" /></td > <td><input type="text" id="name-' + id + '" name="field_name[]" value=""' +
'class="form-control" style="width:100%;" placeholder="Name" /></td></tr ></table >' +
'<a href="javascript:void(0);" class="remove_button"><button type="button"' +
'class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> - Remove </button></a></div >';
}
//Once add button is clicked
$(addButton).click(function () {
//Check maximum number of input fields
if (x < maxField) {
$(wrapper).append(fieldHTML(idCounter++)); //Add field html
x++; //Increment field counter
}
});
//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>
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%" />
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%" />
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field"><button
style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role
</button></a>
</div>
</div>
Note, I have created a new variable idCounter to keep the id unique even when you remove a row. Otherwise, it might create elements with duplicate ids.
This is just one quick way, but there are many other ways this can be achieved. The code can be made mode tidy and readable.

Launching a new window and filling form values using Javascript

I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}

How to determine if the input is of array type in javascript?

<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc

Adding XML attribute from array PHP

I am have a dynamic HTML form (jQuery) that a user can add in an ingredient and its quantity, After the user puts in the data I need to save the data as XML. I was thinking of having the quantity as an attribute of the ingredient tag, so for example
<ingredient quantity="250g"> spaghetti </ingredient>
However at the moment I'm not sure how to pass the information in through my array as only a string is allowed as an attribute. I was wondering if anyone had an idea how to do this?
Here are some snippets of my code.
HTML form:
<div id="addIngredient">
<p>
<input type="text" id="ingredient_1" name="ingredient[]" value="" placeholder="Ingredient"/>
<input type="text" id="quantity_1" name="quantity[]" value="" placeholder="quantity"/>
Add
</p>
</div>
<br />
jQuery:
$('#addNewIngredient').on('click', function () {
$('<p> <input id="ingredient_' + i + '" size="40" name="ingredient[]' + '" type=text" value="" placeholder="Ingredient" /><input id="quantity_' + i + '" size="40" name="quantity[]' + '" type=text" value="" placeholder="Quantity" /> Remove </p> ').appendTo(addDiv2);
i++;
return false;
});
PHP:
$ingredients = $xml->createElement('ingredients');
for ($i = 0; $i < 2; $i++) {
$element = $ingredientName[$i];
$ingredient = $xml->createElement('ingredient_name', $element);
$ingredient->setAttribute("quantity", $quantity);
$ingredients->appendChild($ingredient);
}
$recipe->appendChild($ingredients);

How Could i rearrange textboxes which are named as array index

i am working on a project in which i have to render rows dynamically . but user could also delete that row have a look at my current working
JQuery
var counter = 1;
function addrow() {
var textbox = "<div id='rows" + counter + "'> </br><label> Option : </label><input type='text' name='Answers[" + counter + "]' class='ahsan required' />Remove</div>";
var form = $("#form").valid();
if (form) {
$("#TextBoxesGroup").append(textbox);
counter++;
}
else {
return false;
}
}
html
<div id="TextBoxesGroup" style="margin-left: 100px;">
<div id="rows0">
</br><label>
Option :
</label>
<input type='text' name='Answers[0]' class='ahsan required' />Remove
</div>
</div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' /></div>
Now , if i have 10 rows there names will be Answers[0,1,2,3,4,5] . I want to remove input when i click on remove anchor and also reoder all textbox's name
For Example if i remove input at 4th index then all textbox automatically get re arranged . Can i Do it Please Help me and Thanks in Advance
You can make it without counter. This way your answers will be always ordered in the array starting by zero.
Here's a plausible solution:
$(function(){
$("#form").validate();
this.addrow = function() {
if ($("#form").valid()) {
var textbox = "<div> </br><label> Option : </label><input type='text' name='Answers["+$("#TextBoxesGroup div").length+"]' class='ahsan required' /><a class='remove-me' href='#'>Remove</a></div>";
$("#TextBoxesGroup").append(textbox);
$('.remove-me').click(function(){
$(this).parent().remove();
return false;
});
}
else {
return false;
}
}
this.addrow();
});
and the html is simple like this:
<form id="form">
<div id="TextBoxesGroup" style="margin-left: 100px;"></div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' />
</div>
</form>

Categories