JavaScript add remove fields in dynamically generated forms - javascript

One example on how to use JavaScript to add remove fields in dynamically generated forms.

<h3>javascript add remove fields in dynamically generated forms</h3>
<br>
modification of http://www.quirksmode.org/dom/domform.html
<br>
<br><br>
<?
$action_url = {form action here};
?>
<script type="text/javascript">
var i = 1;
function addCost(cost_no){
cn = cost_no;
//max nubmer of fields, for all cases together
if (i <= 300){
i++;
ident = 'cost['+cn+']['+i+']';
var div = document.createElement('div');
//div.style.width = "300px";
//div.style.height = "50px";
//div.style.color = "white";
div.setAttribute('class', 'myclass');
div.innerHTML = '<input type="text" \n\
name="'+ident+'" \n\
id="'+ident+'" \n\
> \n\
<input type="button" \n\
value="-" \n\
onclick="removeKid('+cn+', this)"\n\
>';
document.getElementById('kids'+cn+'').appendChild(div);
}
}
function removeKid(cost_no, div) {
//alert(test);
cn = cost_no;
document.getElementById('kids'+cn+'').removeChild( div.parentNode );
i--;
}
</script>
<form action="<?= $action_url;?>" method="post" >
<?
for ($cost_id=0; $cost_id<=10; $cost_id++)
{
echo "The form id is : $cost_id <br>";
?>
<div id="kids<?= $cost_id; ?>">
<input type="button"
id="add_cost<?= $cost_id; ?>"
onClick="addCost(<?= $cost_id; ?>)"
value="Add field:<?= $cost_id; ?>"
/>
</div>
<br>
<?
}
?>
<br>
<input type="submit" name="submit" value="submit" />(limit 300)
</form>

Related

Error message for value transfer with dynamic form

i created a dynamic form where you can add a form group. on a second page the input is sent by post. if i add more than one field, the radio buttons don't work anymore and the mail delivery doesn't work either
I tried to make a for-loop, but doesnt worked..
index.php (dynamic form):
<script>
var ct = 1;
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// link to delete extended form elements
var delLink = '<div style="text-align:right;margin-right:65px">Delete</div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
</script>
<style>
#newlink {width:600px}
</style>
<form method="post" action="index2.php">
<div id="newlink">
<div>
</div>
</div>
<p>
<br>
<input type="submit" name="submit1">
</p>
<p id="addnew">
New
</p>
</form>
<div id="newlinktpl" style="display:none">
<div>
<table>
<tr>
<label>Ordner:</label>
<td> <input type="text" name="linkurl[]" value="" placeholder="New Folder" required></td>
</tr>
<tr>
<td>
<label>Write</label>
<input type="radio" name="berechtigung[] " value="W">
</td>
<td>
<label>Read</label>
<input type="radio" name="berechtigung[] " value="R">
</td>
<td>
<label>None</label>
<input type="radio" name="berechtigung[] " value="K ">
</td>
</tr>
</table>
</div>
</div>
index2.php: (POST-DATA)
<?php
if(count($_POST))
{
$len = count($_POST['linkurl']);
for ($i=0; $i < $len; $i++)
{
echo $_POST['linkurl'][$i] . '<br>';
echo $_POST['berechtigung'][$i] . '<br>';
}
}
?>

Result POST Submit inside php form without refresh

i just combine some code to generate some random string, searching from stackoverflow and googling.
How do i get result instantly without page going refresh.
when i press button generate.
here is my code
<?php
function randomString($length = 5) {
$str = "";
$characters = array_merge(range('A','Z'), range('0','9'));
$max = count($characters) - 1;
for ($i = 0; $i < $length; $i++) {
$rand = mt_rand(0, $max);
$str .= $characters[$rand];
}
return $str;
}
?>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>
<?php
$randomprivate = randomString();
if (isset($_POST['submit']))
{
$result = $_POST['firstname']."-".$_POST['lockercode']."-".$randomprivate;
}
?>
<form action="#" method="post">
First name:<br>
<input type="text" name="firstname">
<br>
Locker ID:<br>
<input type="text" name="lockercode">
<br><br>
<input type="submit" name="submit" value="Generate Secret">
<br>
Your Secret Identifier:<br>
<input type="text" value="<?php if (isset($result)) echo $result ?>" readonly>
<br><br>
<button onclick="goBack()">Go Back</button>
</form>
<script>
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
document.getElementById("mytext").value = text;
}
</script>
<form action="#" method="post">
First name:<br>
<input type="text" name="firstname">
<br>
Locker ID:<br>
<input type="text" name="lockercode">
<br><br>
<input type="submit" name="submit" value="Generate Secret" onclick="makeid()">
<br>
Your Secret Identifier:<br>
<input id="mytext" type="text" readonly>
<br><br>
<button onclick="goBack()">Go Back</button>
</form>

Loop through inputs and get checked value

I'm trying to get a list of radio inputs from a form that are grouped by their names, and they all have different names. I'm trying to create an array with them, if they are checked then append a 1 to the array, otherwise append a 0. None of the alert boxes pop up, so I assume that the function processDataForFinalization doesn't get called.
I didn't know if something was wrong with how I'm appending to the array. Or if it's a bigger error than that.
Thanks in advance.
EDIT4 Here is the updateBallot.php code
TwoResults.txt looks like:
0 0 0 0 0 0 0 0
3 4 1
<?php
$name = $_POST['name'];
$points = $_POST['points']; //array of user vote
echo $points;
$txt_file = file_get_contents($name.'Results.txt');
$rows = explode("\n", $txt_file); // rows-array separated by new line
foreach($rows as $row => $data)
{
$row_datas = explode(' ',$data);
}
$goods = $row_datas[0];
$goodies = $row_datas[1];
$newArr = [];
for($j=0;$j<count($points);$j++) {
$newArr[$j] = $goods[$j] + $points[$j];
}
$newText = "";
foreach($newArr as $nArr => $nData) {
$newText .= $nData." ";
}
$newText .= "\n";
$secondNewArr = [];
$sizeOfBottom = count($goodies);
for($k=0;$k<$sizeOfBottom;$k++) {
$secondNewArr[$k] = $goodies[$k];
}
foreach($secondNewArr as $neArr => $neData) {
$newText .= $neData." ";
}
$myFile = fopen($txt_file,"w+");
fwrite($myFile, $newText);
fclose($myFile);
?>
EDIT3 Here is the output HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="20">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="Array">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
</div>
<script>
var numQs = 1;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
</div>
<script>
var numQs = 2;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input2" value="1">
a <br>
</div>
<script>
var numQs = 3;
</script>
<br><br><br>
<div class="submit">
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</div>
</form>
EDIT2 Here is the HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="<?php echo $arr;?>">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<?php
if (file_exists($name.'.txt')) {
if($type==1) {
$inputType = "checkbox";
} else {
$inputType = "radio";
}
$txt_file = file_get_contents($name.'.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
$vals = 0;
foreach($rows as $row => $data)
{
$arrCount = 0; // number of elements in array
echo "<div id='ballotElement'>";
$row_data = explode('^',$data);
$info[$row]['questions'] = $row_data[0];
$info[$row]['answers'] = $row_data[1];
echo "<h4><u>".$info[$row]['questions'] . "</u></h4>";
//echo $info[$row]['answers'] . "<br>";
$lines = explode("~",$info[$row]['answers']);
foreach($lines as $line => $lData) {
$answers[$row][$line] = $lData;
if($answers[$row][$line] !== "") {
$arrCount++;
?>
<input type="<?php echo $inputType; ?>" name="input<?php echo $row; ?>" value="1">
<?php echo $answers[$row][$line]; ?>
<br>
<?php }
$vals++;
}
if($writeIn == "y") {
$arrCount++; ?>
<input type="text" name="writeIn<?php echo $row; ?>" placeholder="Write in">
<?php
}
echo "</div>";
array_push($arr, $arrCount);
?>
<script>
var numQs = <?php echo count($arr); ?>;
</script>
<?php
}
} else {
header('Location: error.php');
}
echo "<br><br><br>";
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</form>
EDIT getActualData() is called from getData()
Here is getData(), this function works, so I'm not sure why the getActualData() doesn't work since they are basically the same thing.
function getData() {
var parts = 0;
for(var i=0; i<numQs; i++){
var checked = false;
var inp = document.getElementsByName('input'+i);
for(var j=0; j<inp.length && checked == false; j++){
if(inp[j].checked) {
checked = true;
parts++;
}
}
}
if(parts != numQs){
window.alert('Please vote for at least one candidate per race.');
return false;
} else {
window.alert('Okay');
getActualData();
//return true;
}
}
function processDataForFinalization() {
$.ajax({
url: 'updateBallot.php',
type: 'post',
data: {"points" : val, "name":name},
success: function(data) {
// Do something with data that came back.
window.alert(data);
//return true;
}
});
}
var val = [];
function getActualData() {
for(var k=0;k<numQs;k++) {
var inpu = document.getElementsByName('input'+k);
for(var jk=0;jk<inpu.length;jk++) {
window.alert('almost there');
if(inpu[jk].checked) {
window.alert('hello');
val.array_push(1);
window.alert(val.length);
} else {
val.array_push(0);
}
}
}
processDataForFinalization();
}

I want to sum the looped textbox

Hi guys I am new to javascript and php and I have a problem
I'd like to sum the looped text box but I am lack at logics
here is the code
<form name="rec" action="this.php" method="post" >
<?php
$x = 0;
while($x<=5){
$x++;
echo "<input type='text' name='n". $x."' id='n". $x."'>< input type='text' name='y". $x."' id='y". $x."'>
<input type='text' name='res". $x."' id='res". $x."'>";
}
?>
<input type="button" value="Compute" onclicked="compute()">
</form>
< script >
ctr = 0<
while(ctr<=5){
ctr++;
x = Number(document.getElementById("n"+ctr).value)
y = Number(document.getElementById("y"+ctr).value)
ans = x+y;
document.getElementById("res"+ctr).value = ans;
}
< /script>
I would like to get the out put of like this
Thank you I am not really specific :D
try this
<form name="rec" action="#" method="post">
<?php
$x = 0;
while($x<=5){
$x++;
echo "<input type='text' name='n". $x."' id='n". $x."'><input type='text' name='y". $x."' id='y". $x."'>
<input type='text' name='res". $x."' id='res". $x."'><br>";
}
?>
<input type="button" value="Compute" onclick="compute()">
</form>
<script>
function compute()
{
var ctr = 0;
while(ctr<=5){
ctr++;
var x = Number(document.getElementById("n"+ctr).value);
var y = Number(document.getElementById("y"+ctr).value);
var ans = x+y;
document.getElementById("res"+ctr).value = ans;
}
}
</script>
Where is your compute function? You should enclose the contents of the <script> tag with function compute().

Javascript Add New Input Field in Increasing Order

I'm having trouble getting my javascript to add a variable to getElementById. What I'm doing is allowing the users to have 10 authors per post. The script shows the authors already entered in the system and now I'm trying to allow them to add more input fields only to the point that 10 fields show up. Here is the code I have so far:
$y=1;
//GET EXISTING AUTHORS FOR POST
while ($getauthorsrow=$getauthorssql->fetch()) {
$showauthor = $getauthorsrow['author'];
$authorid = $getauthorsrow['ID'];
echo "<input type='text' value='$showauthor' name='authorname[]'>
<input type='hidden' value='$authorid' name='authorid[]'><br><br>";
$y++;
}
$newy=$y-1;
?>
//SCRIPT TO ADD NEW FIELD ONLY TO THE POINT OF 10
<script language="javascript">
fields = <?php echo $newy; ?>;
function addInput<?php echo $i; ?>() {
if (fields != 10) {
//HERE I'M TELLING IT TO GET text + $i (which is post number) + fields variable
//So if it's the first post and the new field divs start a 5
//Then it should getElementByid('text05') and continue on.
document.getElementById('text<?php echo $i; ?>' + fields).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
document.getElementById('text<?php echo $i; ?>' + fields).innerHTML += "<br />Only 10 authors allowed.";
document.ajaxform<?php echo $i; ?>.add<?php echo $i; ?>.disabled=true;
}
}
</script>
//HERE I'M ADDING THE NEW DIVS FOR TEXT FIELDS AND STARTING
//THEM AT WHATEVER NUMBER POST $i IT IS AND WHATEVER THE $w is.
//SO IN THE EXAMPLE IN THE JAVASCRIPT IT'D SAY id='text05'
//THIS WORKS JUST FINE
<?php
$w=$newy;
while ($w<=10) {
echo "<div id='text".$i.$w."'></div>";
$w++;;
}
//ECHO THE ADD AUTHOR BUTTON
echo "
<input type='button' onclick='addInput$i()' name='add$i' value='Add Author'><br>
<input type='hidden' name='count' value='$newy'>
<input type='hidden' name='id' value='$fileid'>
<input type='submit'>
</form>
";
?>
$i is the post number starting from 0. The php to make the divs works fine. I'm just getting null for the getElementById in the javascript. What am I getting wrong here?
HTML Output Example:
<form id="ajaxform0">
<input type="text" value="Logan" name="authorname[]">
<input type="hidden" value="121" name="authorid[]"><br><br><input type="text" value="Matt" name="authorname[]">
<input type="hidden" value="122" name="authorid[]"><br><br><input type="text" value="Chad" name="authorname[]">
<input type="hidden" value="123" name="authorid[]"><br><br><input type="text" value="hey" name="authorname[]">
<input type="hidden" value="128" name="authorid[]"><br><br><input type="text" value="jordan" name="authorname[]">
<input type="hidden" value="129" name="authorid[]"><br><br>
<script language="javascript">
fields = 5;
function addInput0() {
if (fields != 10) {
var currentText = 'text0' + fields;
document.getElementById(currentText).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
document.getElementById(currentText).innerHTML += "<br />Only 10 authors allowed.";
document.ajaxform0.add0.disabled=true;
}
}
</script>
<div id="text05"></div><div id="text06"></div><div id="text07"></div><div id="text08"></div><div id="text09"></div><div id="text010"></div>
<input type="button" onclick="addInput0()" name="add0" value="Add Author"><br>
<input type="hidden" name="count" value="5">
<input type="hidden" name="id" value="45">
<input type="submit">
</form>
Try assigning that concatenated string to a JS variable first, then calling the function:
if (fields != 10) {
var currentText = 'text<?php echo $i; ?>' + fields;
document.getElementById(currentText).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
document.getElementById(currentText).innerHTML += "<br />Only 10 authors allowed.";
document.ajaxform<?php echo $i; ?>.add<?php echo $i; ?>.disabled=true;
}
I need to add the $i to the fields variable in the javascript. With multiple files it was doing multiples of the same variable...i works.
Hi I have modified your code for html and JavaScript.
<form id="ajaxform0">
<input type="text" value="Logan" name="authorname[]">
<input type="hidden" value="121" name="authorid[]"><br><br><input type="text" value="Matt" name="authorname[]">
<input type="hidden" value="122" name="authorid[]"><br><br><input type="text" value="Chad" name="authorname[]">
<input type="hidden" value="123" name="authorid[]"><br><br><input type="text" value="hey" name="authorname[]">
<input type="hidden" value="128" name="authorid[]"><br><br><input type="text" value="jordan" name="authorname[]">
<input type="hidden" value="129" name="authorid[]"><br><br>
<script language="javascript">
fields = 5;
function addInput0() {
if (fields != 10) {
var currentText = 'text0' + fields;
document.getElementById(currentText).innerHTML += "<center><input type='text' name='newauthorname[]'></center><br /><br />";
fields += 1;
} else {
var myout = "Only 10 authors allowed.";
document.getElementById("stat").innerHTML = myout;
}
}
</script>
<div id="text05"></div><div id="text06"></div><div id="text07"></div><div id="text08"></div><div id="text09"></div><div id="text010"></div><div id="stat"></div>
<input type="button" onclick="addInput0()" name="add0" value="Add Author"><br>
<input type="hidden" name="count" value="5">
<input type="hidden" name="id" value="45">
<input type="submit">
Check it and let me know, if it is solved.

Categories