I have some code I am using that works well cloning the contents of a div as many times as needed.
The original code would rename the name/id of each form field. so the first clone the name would be "name1" second clone "name2" etc...
The problem is when I put the form fields within a div or a table for design purposes.
The code doesn't rename the form fields anymore as it seems to refer to the top elment which is the table or div (depending which I used)
Here is a cut down version of the code that contains everything needed for this example (can be copied into an editor and will work as is. You will see the field id's are not being renamed):
www.jsbin.com/oyavez/1/edit
<script type="text/javascript">
var formCounter = 0;
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
formCounter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + formCounter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
<title>Add Orders IO TOC</title>
</head>
<body>
<!-- Template -->
<div id="readroot" style="display: none">
<table>
<tr><td colspan="2"><h3>Order <script>document.write(formCounter);</script></h2></td></tr>
<tr><td>Order ID: </td><td><input type="text" id="OrderID name="OrderID[]" ></input></td>
<td>Order Name: </td><td><input type="text" id="OrderName" name="OrderName[]" ></input></td>
</table>
<br /><br /><input type="button" value="Remove Above Order" style="width:200px;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<!-- ROW -->
</div>
<!-- END Template -->
<!-- Start of form -->
<form method="get" action="form.php">
<table>
<tr><td align="center" colspan="2"><h2>Contract</h2></td></tr>
<!-- Static part of the form not to be cloned -->
<tr><td>Contract: </td><td><input type="text" id="Contract" name="Contract" ></input></td>
<td>Signed Date: </td><td><input type="text" id="datepicker0" name="SignedDate" ></input></td>
<tr><td align="center" colspan="2"><h2>Orders</h2></td></tr>
</table>
<!-- ROW -->
<!-- Cloned parts of the form appear here -->
<span id="writeroot"></span>
<table>
<tr><td align="center" > <input type="button" style="width:200px;" value="Add another order below" onclick="moreFields()" /></td>
<td align="center" ><input type="submit" value="Submit IO and all Orders" style="width:200px;" ></td></tr>
</table>
</form>
Anyone know how to get to the child of the table it would seem?
Thanks!
Related
I can't find the average of all the inputs. My code only reads the input that i stated in html, but doesn't read the other dynamic ones.
Heres my code:
$(document).ready(function(){
// adds a new row
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
// deletes the row
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
$("#customFields").on('click','.add',function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
$("#click").click(function(){
var isbn = document.getElementById('customFieldName').value;
alert(isbn / $("input").length)
$("#averageGrade").text("Average Grade: " + isbn)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label for="customFieldName">Custom Field</label></th>
<td>
<input type="text" class="code" id="customFieldName" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id = "click" class = "btn btn-primary" >Hi</button>
<p id = "averageGrade">Average Grade:</p>
Please help!
Thanks!
Each element.id must be unique - please change customFieldName to a class, and then iterate over the inputs and calculate the average. Also, you can reuse the same class for all "add" buttons and save that string in a variable so you don't have to paste it multiple times.
let inputTemplate = '<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="text" class="customFieldName code" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>';
$(document).ready(function() {
// adds a new row
$("#customFields").on('click', '.addCF', function() {
$("#customFields").append(inputTemplate);
});
// deletes the row
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
$("#click").click(function() {
let fields = $('.customFieldName'),
total = 0;
for (let field of fields)
total += Number(field.value);
let average = total / fields.length;
$("#averageGrade").text("Average Grade: " + average);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="text" class="customFieldName code" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id="click" class="btn btn-primary">Hi</button>
<p id="averageGrade">Average Grade:</p>
First of all, you need a way to select all the fields. Since id must (should) be unique, you could use the name or the class .code and remove id="customFieldName".
Then, getElementById, as its name suggests, returns one element. You need to select them all! If you're using class names, you can use getElementsByClassName, or querySelectorAll, or, since you're already using jQuery, just $(".code"), along with a loop to read each input's value (it you use jQuery, you can also use each()).
var sum=0,count=0,average;
$(".code").each(function() {
var value=parseInt($(this).val());
//You may want to validate the field
if(!isNaN(value)) sum+=value;
count++;
});
average=sum/count;
...
As many has pointed out (including myself in the comment section), you are going about using the wrong selector. id is a unique selector, meaning that the script will look at the first instance of the id and then stop immediately after.
What you need to do is use a selector that goes through every occurance of its instance. This is why class selectors exist. That will be the first fix in your code.
How I would go about calculating the average, personally, would be to make an array and push(); the values of the grades into the array. We will also need to do a parseInt() to make sure that our values are in fact handled as numbers. Otherwise, they'll be interpreted as strings.
You will then need to loop through the array, sum the values and divide by the length of the array.
HTML Example:
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
jQuery Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
Codepen example can be found here.
Snippet Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
I am looking to calculate a column within a table that is being created. I need the sum field to add up the values created from the form, which is created new rows for the table upon submit. Any way I can get the to add up the column sum? Each time a function updatetable() is run is creates another table row, and these are the rows I need calculated...currently the column holds a "184" as a holding place for where the calculation would take place.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>The real test</title>
<link rel="stylesheet" href="html_testing.css">
<script type="text/javascript"> <!--
var tabBody, row, cell;
function updateTable(){
tabBody=document.getElementById("joe$");
row=document.createElement("tr");
row.setAttribute("id","js");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[2].value;
row.appendChild(cell);
if(tabBody.childNodes.length==17)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
function updateTable1(){
tabBody=document.getElementById("joe");
row=document.createElement("tr");
cell = document.createElement("td");
cell.innerHTML=document.forms['leds'].elements[3].value;
row.appendChild(cell);
if(tabBody.childNodes.length==17)
tabBody.removeChild(tabBody.childNodes[0])
tabBody.appendChild(row);
}
function myFunctionJoe(){
updateTable();
updateTable1();
}
function moneymoney(){
('#joe$ tr:first td').each(function(){
var $td = $(this);
var colTotal = 0;
$('#joe$ tr:not(:first,.totalColumn)').each(function(){
colTotal += parseInt($(this).children().eq($td.index()).html(),10);
});
$('#joe$ tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});
}
</script>
<body>
<h2>Legion of Roar:</h2>
<form name="leds" id="ledSend" action="" onsubmit="return false;">
Lamp Control: <input type="radio" name="led" value="0" checked />Off
<input type="radio" name="led" value="1" />On<br>
Winning Bid: <input type="text" name="timer" placeholder="Bid..." /><br>
Player Drafted: <input id="name" type="text" name="user" placeholder="Player Name..." /><br>
Player Position: <input id="name" type="text" name="user" placeholder="Position..." /><br>
<br>
<input type="submit" value="Joe" onclick="myFunctionJoe();"/>
<h1>Testing some skills</h1>
<fieldset>
<table border ='1' class="inlineTable">
<thead><tr><th>Joe</th></tr></thead>
<thead><tr><th>200</th></tr></thead>
<tr class="totalColumn">
<td class="totalCol">Spent:</td>
</tr>
<tbody id="joe"><tbody>
</table>
<table border ='1' class="inlineTable">
<thead><tr><th>$</th></tr></thead>
<thead><tr><th>184</th></tr></thead>
<tr class="totalColumn">
<td class="totalCol">Spent:</td>
</tr>
<tbody id="joe$"><tbody>
</table>
</body>
</html>
I am adding rows using java script functions by taking input and showing data into input text fields.
I am using this datepicker https://github.com/T00rk/bootstrap-material-datetimepicker.
When I input time the only first value of time is copied into input fields while rest two value are copied but time value is not copied.
<div style="width:90%;margin:auto;">
<h1>Simple example of dynamically adding rows with jQuery</h1>
<form method="post">
<div id="itemRows">
Item quantity: <input type="text" name="add_qty" size="4" /> Item name: <input type="text" name="add_name" />Time:<input type="text" id="time" name="time" />
(This row will not be saved unless you click on "Add row" first)
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
<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+'">Time<input type="text" id="time" name="time[]" size="4" value="'+frm.time.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 = '';
frm.time.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
When you generate dynamic textbox with id and with date picker so you need to call one function for init datepicker on that text like below
$('input').bootstrapMaterialDatePicker();
function addRow(frm)
{
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time'+rowNum+'" name="time[]" size="4" value="'+frm.time.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 = '';
frm.time.value = '';
$('#time'+rowNum).bootstrapMaterialDatePicker();
}
In above function i add one id to time textbox and call bootstrap datepicker to init date on that textbox.
See working demo here
http://plnkr.co/edit/P0ZQsAjDJAXyJGs9kvT3?p=preview
I have a form that a user can fill out.
What i want to be able to do is allow to user to add more feilds if needed.
All works wells expect for one small part i cannot seem to get around. I have spent the last couple days trying to figure it out and its driving me crazy.
Javascript Code
<script>
var ed = 1;
function new_education()
{
ed++;
var div1 = document.createElement('div');
div1.id = ed;
var delLink = '<a class="btn btn-danger" style="text-align:right;margin-right:65px" href="javascript:deled('+ ed +')" > Delete Education ' + ed + ' </a>';
document.getElementById('educationtr').innerHTML = '<th colspan="4" style="background-color:#b0c4de;">Education ' + ed + '</th>';
div1.innerHTML = document.getElementById('educationtpl').innerHTML + delLink;
document.getElementById('education').appendChild(div1);
}
function deled(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('education');
parentEle.removeChild(ele);
ed--;
}
</script>
HTML Code
<legend>Education</legend>
<div id="education">
<table border=3>
<tr><th colspan="4" style="background-color:#b0c4de;">Education 1</th></tr>
<tr><td><label>School Name</label><input type="text" name="schoolname[]" maxlength="30" size="30"><br></td>
<td><label>Degree Type</label><input type="text" name="degreetye[]" maxlength="30" size="30"><br></td>
<td><label>Degree Field</label><input type="text" name="degreefield[]" maxlength="30" size="30"><br></td>
</tr></table>
</div>
<a class="btn btn-info" href="javascript:new_education()" > Add New Education </a>
<div id="educationtpl" style="display:none">
<table border=3>
<tr id="educationtr"></tr>
<tr><td><label>School Name</label><input type="text" name="schoolname[]" maxlength="30" size="30"><br></td>
<td><label>Degree Type</label><input type="text" name="degreetype[]" maxlength="30" size="30"><br></td>
<td><label>Degree Field</label><input type="text" name="degreefield[]" maxlength="30" size="30"><br></td>
</tr></table>
</div>
jsfiddle example not working however http://jsfiddle.net/811yohpn/
Working Example: http://thenerdservice.com/addtest.php
What I would like to happen is each new table added will get a new heading "Education 2", "Education 3" etc but that does not happen.
What happens is when the button is hit to add new table the tr data will appear correct.
If you hit it once more it will increment the tr data however the delete buttons stay
correct.
If you hit the button more times the top tr data will continue to increment however the reat of the added tr data stays "Education 2"
Thank you
What I suggest is to rewrite new_education function using jQuery (I have tried to save most part of original code, but it wasn't so easy) fixing this problem with multiple same IDs.
Updated fiddle.
function new_education() {
ed++;
var newDiv = $('#education div:first').clone();
newDiv.attr('id', ed);
var delLink = '<a class="btn btn-danger" style="text-align:right;margin-right:65px" href="javascript:deled(' + ed + ')" > Delete Education ' + ed + ' </a>';
newDiv.find('tr:first th').text('Education ' + ed);
newDiv.append(delLink);
$('#education').append(newDiv);
}
Note: I also changed HTML, removing unnecessary extra table and wrapping first one with <div id="1"></div>:
<legend>Education</legend>
<div id="education">
<div id="1">
<table border=3>
<tr>
<th colspan="4" style="background-color:#b0c4de;">Education 1</th>
</tr>
<tr>
<td>
<label>School Name</label>
<input type="text" name="schoolname[]" maxlength="30" size="30"/>
</td>
<td>
<label>Degree Type</label>
<input type="text" name="degreetye[]" maxlength="30" size="30"/>
</td>
<td>
<label>Degree Field</label>
<input type="text" name="degreefield[]" maxlength="30" size="30"/>
</td>
</tr>
</table>
</div>
</div>
<br/>
<a class="js-addNew btn btn-info" href="javascript:new_education()"> Add New Education </a>
The following code was working very well. Suddenly, the Edit button click stopped working. When the user used to click Edit button, a JSON code executed. But it is not recognizing the click now. Something happened accidentally? Please assist.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></meta>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script src="js/calendar.js" type="text/javascript"></script>
<link href="js/calendar.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="css/wysiwyg.css" type="text/css">
<script type="text/javascript" src="js/wysiwyg.js"></script>
<script type="text/javascript" src="js/wysiwyg-settings.js"></script>
<!-- JSON implementation to get data through JQuery/AJAX -->
<script type="text/javascript">
$(document).ready(function(){
$("#Edit").click(function(){
$.getJSON("fetchvalues.php?UpdateRecordID=" + $.cookie('UpdateRecordID'),
function(data){
//Fill the Form with the data values
document.getElementById('LDate').value = data[0];
document.getElementById('Places').value = data[1];
document.getElementById('Company').value = data[2];
document.getElementById('Designation').value = data[3];
document.getElementById('ProjectDetails').value = data[4];
document.getElementById('DesiredCandidate').value = data[5];
document.getElementById('HRName').value = data[6];
document.getElementById('HRContact').value = data[7];
document.getElementById('Email').value = data[8];
});
});
});
</script>
<title>Job Listing Entry</title>
</head>
<body>
<table id="main" cols="2">
<tr>
<td>
<Form id="frmNewEntry" method="post" action="insert_listing.php">
<table id="tblEntry" cols="3" style="border-color:lightblue; border-style:solid;">
<tr><td colspan="3" bgcolor="lightblue" align="center"><strong>Real-Time Vacancy Entry</strong></td></tr>
<tr><td>Date:</td><td><input id="LDate" name="LDate" type="text" size="20" maxlength="11"/>[Select Date from the Calendar Control]
<script type="text/javascript">
WYSIWYG.attach('all', full);
calendar.set("LDate");
</script></td>
<td>
<table>
<tr>
<td rowspan="6">
<!-- <iframe src="show_db_vacancy_entries.php" height="800px" width="300px" bordercolor="cyan">
</iframe> -->
</td>
</tr>
</table>
</td>
</tr>
<tr><td>Places:</td><td><input id="Places" name="Places" type="text" size="35" maxlength="30" onblur="this.value=MakeInitialCapital(this.value);"></td></tr>
<tr><td>Company:</td><td><input id="Company" name="Company" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">
<!-- <input type="button" value="Make Initial Capital" align="left" onclick="this.value=MakeInitialCapital(this.value);"></tr> -->
<tr><td>Designation:</td><td><input id="Designation" name="Designation" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);"></td></tr>
<tr><td>Project Details:</td><td><textarea id="ProjectDetails" name="ProjectDetails" cols="100" rows="10"></textarea></td></tr>
<tr><td>Desired Candidate:</td><td><textarea id="DesiredCandidate" name="DesiredCandidate" rows="3" cols="100"></textarea> <br></td></tr>
<tr><td>HR Name:</td><td><input id="HRName" name="HRName" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);"> <br></td></tr>
<tr><td>HR Contact:</td><td><input id="HRContact" name="HRContact" type="text" size="50"> <br></td></tr>
<tr><td>Email:</td><td><input id="Email" name="Email" type="text" size="50"> <br></td></tr>
<tr></tr>
<tr>
<td bgcolor="lightblue">
<input id="Clear" name="Clear" value="Clear" type="button" onclick="ClearFields();">
</td>
<td bgcolor="lightblue">
<input id='Submit' name='Submit' value='Submit' type='submit' />
</td>
</tr>
</table>
</Form>
</td>
<td>
<table id="list" cols="2" style="border:none">
<tr>
<td colspan="2" style="border:none">
<iframe src="show_db_vacancy_entries.php" height="600px" style="border:none;">
</iframe>
</td>
</tr>
<tr>
<td align="left">
<input id="Edit" name="Edit" value="Edit Record" type="button" />
</td>
<td align="right">
<input id="Delete" name="Delete" value="Delete" type="button" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script language="JavaScript" type="text/javascript">
function MakeInitialCapital(str)
{
return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
function cnvrt() {
return arguments[0].toUpperCase();
}
}
//Convert initials to capital in a certain control
function MakeInitialCapitalControl(controlName)
{
var ctrl = document.getElementById(controlName).value;
if(/^[A-Z]/.test(ctrl.value)) {
ctrl.value = ctrl.value.toLowerCase();
return;
}
/* ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function {
return arguments[0].toUpperCase();
});*/
}
function ClearFields()
{
document.getElementById('Email').value = "";
document.getElementById('HRContact').value = "";
document.getElementById('HRName').value = "";
document.getElementById('DesiredCandidate').value = "";
document.getElementById('ProjectDetails').value = "";
document.getElementById('Designation').value = "";
document.getElementById('Company').value = "";
document.getElementById('Places').value = "";
document.getElementById('LDate').value = "";
}
</script>
I've tested the code, after removing all the external JS and CSS files, and it seems to work fine.
The problem is most likely with the JSON data that you are getting back. Perhaps you did something to the PHP file it is calling, so that the JSON object is malformed, or there is a PHP warning being printed. (Could be a result of a change in the PHP configuration, too)
I would suggest that you try using the page in Firefox with the Firebug addon active (or something equivalent). It will show you exactly what the JSON request is returning, and whether there are any errors with the request.
As Atli said, the code looks fine. Im curious about this $.cookie('UpdateRecordID'), being part of the querystring. What happens if the cookie is not set?
Can you verify a proper response via firebug?