JS to add form fields with a button - javascript

How I create a do...while loop (or if there is a better way to go about this - please advise) for a form with potentially additional information?
Background - I've got a form that will accept a users assessment of a particular location (such as a basement). Using only 1 location per form, this works nicely and submits to my db without a problem.
Now I want to enhance this form with a "add new location" button. I don't (obviously) want to create new pages but rather a loop that can store the first location, save it (which I know could be done with be a session variable) and then clear the fields for locations 2, 3, 4, etc.
My confusion is around the functionality of the button. What type of button is this? Reset with a unique id such as new_loc[]?
And then when I write this as a do...while loop should I do it like this:
<?php
do {
all my form fields
} while (some condition that looks for the button submit);
?>
ok so I have a created a simple JS that can "handle" this.
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " locations");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><br><input type='text' name='location[]'>";
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
Now the problem is that JS will add 1 new field - any suggestions on how to add a massive block of HTML to the JS? I tried adding all my fields to the JS and I get a whole bunch of unclosed string errors.

So first of all your form must have action="" method="post"
then add this php to your page:
session_start();
if (isset ($_POST['NameOfSubmitButtonInsideForm'])) {
if (!isset ($_SESSION['sessionName'])) {
$_SESSION['sessionName'] = 1
}
for ($i = 0; $i <= $_SESSION['sessionName']; $i++) {
echo 'some html code like a form with a input that has
<input type="submit" name="submit- . $i .'EndInputTag>';
};
}
So this will loop the number of times the user clicked the button and you can echo out html code based on that number, or what ever it is you need to do in the loop.

Ok I've figured this out. Thanks to Marc B for suggesting JS.
HTML for the button
<input style="margin-left:5px;" class="btn btn-primary" type="button" value="Add Additional Location" onClick="addInput('locInformation');">
JS
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<h3>Location " + (counter + 1) + "</h3>" + document.getElementById('additionalLoc').innerHTML;
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
And then lastly is the new locInformation stuff:
<div id="additionalLoc" language="text">
huge block of HTML with additional fields
</div>

Related

How to remove a specific clone created with javascript in html when a button is pressed inside that cloned div

The code I have created clones a div section when I press the "Add Co-Pi" btn. Inside my clone creator function (JS) I specify the id's I want for each clone to have.
I have now added a delete button inside the div in order to eliminate the cloned div in which the button finds it self in. Problem is, I can't seem to find how to obtain the div id in which all my elements are inside at the moment of pressing the delete button. I know I can manually type the div name and send it as a parameter to the delete function, but, I want the delete button to automatically extract the div id and send it to the delete function.
I know I might not be explaining myself properly, I am new at using javascript and html.
All help is appreciated. Thank you.
Here is my code. I am using php, html, javascript and sql.
html:
<div id="dynamicInputCoPi">
<!-- <select id='Co_PI_Query' name='Co_PI_Query' onClick= "showId(this.id);"> -->
<select id='Co_PI_Query' name='Co_PI_Query' onClick="copiSelection(1);">
<?php
//This code shows all the selected values from the co-pi table and displays them in a dropdown menu.
//The value is selected by the idCoPI
//First Query //Select * could be changed to select specified data to be shwn
$query = "SELECT *
FROM co_pi_table
";
/** */
//Checks to see if query is successful
$result = mysqli_query($conn, $query);
if($result == false){
die ('<br>Error in Query to CoPI Database Table : ' . mysqli_error($conn));
}
?>
<option value="">**Click here to select Co-PI**</option>
<?php
//echo "I am here";
//Start While
while ($row = mysqli_fetch_array($result)) {
?>
<!-- Options inside the DropMenu will be populated by the query -->
<option value=" <?php echo $row['idCoPI'];?> ">
<?php //echo $row['idCoPI'] . " | " . $row['Fname'] . "-" . $row['Lname'];
echo $row['Fname'] . ", " . $row['Lname'] . "-" . $row['SLname'];
?>
</option>
<?php
} //End of While
?>
</select>
<input type="button" value="+ Add Co-Pi" onClick="openCoPiWin();">
<input type="button" id="Reload_Query" value="Refresh Query" onClick="reloadQuery();">
<br>
<!--
<input type="button" id="Add_Query" value="Select another Co-Pi" onClick="duplicateDivSection(dynamicInputCoPi);">
-->
<input type="button" id="Add_Query" value="Select another Co-Pi" onClick="duplicateDivSection();">
<br>
<input type="button" id="Delete_Query" value="Delete this selection" onClick="deleteClone(document.getElementById('dynamicInputCoPi1'));">
<br>
</div>
</div>
Javascript:
//This function adds another Co-PI dropdown menu to select from when button "Add" is pressed
//document.getElementById('Add_Query').onclick = duplicateDivSection;
var counter = 1;
//var limite = 5;
//var original = document.getElementById('dynamicInputCoPi');
function duplicateDivSection(){
document.getElementById('Add_Query').onclick = duplicateDivSection;
//var counter = 1;
var limite = 5; //Final dynamicInputCoPi value will be "dynamicInputCoPi4"
var original = document.getElementById('dynamicInputCoPi');
//var original = document.getElementById(divName);
if (counter == limite) { //Final dynamicInputCoPi value will be "dynamicInputCoPi4"
//alert("You have reached the limit of adding " + i + " Co-PI or Co-Investigators");
var return_Function = return_coPiCounting();
alert("You have reached the limit of adding " + counter + " Co-PI or Co-Investigators.\n" + "Amount of total coPi entered is: " + return_Function );
}
else {
var clone = original.cloneNode(true); // "deep" clone. "true" means clone all childNodes and all event handlers
//clone.id = divName + counter;
//clone.id = divName + (i);
clone.id = "dynamicInputCoPi" + (counter); //This id will become "dynamicInputCoPi1" the first time it runs
// or clone.id = ""; if the divs don't need an ID
clone.getElementsByTagName('select')[0].id = "Co_PI_Query" + counter; //Changes id of clone
clone.getElementsByTagName('select')[0].name = "Co_PI_Query" + counter; //Changes name of clone
clone.append('<input type="button" value="Delete Co-PI" name="Delete_CoPI">'); //Adds another button to delete form selection
original.parentNode.appendChild(clone); //appends all changes to new clone
//i++;
//counter = counter + 1;
counter++;
coPiCounting(counter);
return false;
}
}
//*******************************************************************************************************************
//Deletes last co-pi selection
function deleteClone(toDelete){
$(toDelete).remove();
//counter--;
}
You can add an event listener on the clones delete button as you create it. When the deleteClone function is called, this will refer to the input that was clicked. From that input reference we can get the parent (which is the div of that clone) and remove it- you don't even need the div id.
Here is an example that uses createElement to create the delete button and add the event listener to it.
var original = document.getElementById("dynamicInputCoPi");
for (var i = 1; i <= 3; i++) {
cloneOriginal(i);
}
function cloneOriginal(counter) {
var clone = original.cloneNode(true);
clone.id = "dynamicInputCoPi" + counter;
clone.appendChild(createDeleteButton(counter));
original.parentNode.appendChild(clone);
counter++;
}
function deleteClone() {
this.parentNode.remove();
}
function createDeleteButton(counter) {
var deleteElem = document.createElement("input");
deleteElem.type = "button";
deleteElem.value = "Delete Co-PI " + counter;
deleteElem.name = "Delete_CoPI";
deleteElem.addEventListener("click", deleteClone);
return deleteElem;
}
<div id="container">
<div id="dynamicInputCoPi">
<p> hello </p>
</div>
</div>

Send javascript generated texbox values with form(GET) to PHP script

I have a form where you can generate automatically additional form boxes and send them to be handeled at PHP-script. How ever as I am quite lousy with Javascript and I am running in the following problem.
When the form is filled out I can see everything is filled out on the URL, except the the boxes created with JS (every box has unique name!). My guess is that the JS generated field drop out of the form tags, but can not figure out how to fix this. I would appreciate if someone could give me pointers or tell me how to fix this. I shortened the code for clarity (if something got left out please tell me). If someone is wondering why I am not using the form action. It´s because drupal tries to forward the site to wrong place if I do (surprise, not too good with drupal either :D)
<?php
require_once('customer.php');
?>
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "<div class='product'><tr><td>Sku/ID: "+intTextBox+": <input type='text' name='sku_" + intTextBox + "'/></div>";
contentID.appendChild(newTBDiv);
}
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
<table>
<form name="activate">
<div class='cu'>
<tr><td>Sku/ID (oma): <input type="text" name="sku"></td>
<td><p><a href="javascript:addElement();" >Add product</a>
<a href="javascript:removeElement();" >Remove product</a></p></td></tr>
<div id="content"></div>
</div>
<tr> <td><input type="submit" value="Submit"></td> </tr>
</form>
Customer.php
<?php
if(isset($_GET["sku_1"]))
{
echo "found it";
}
else
echo "did not find it";
?>
Any help would be much appreciated!
You could dynamically change the url of the form tag to include textbox values:
var textboxes = document.getElementsByTagName("input");
for (var i = 0; i < textboxes.length; i++){
var data = "?";
if (textboxes[i].type == "text") {
data += (data == "?" ? "" : "&") + textboxes[i].name + "=" + textboxes[i].value;
}
}
form.action += data;
I haven't tested this, you might have to dynamically add all elements
[UPDATE]
If you have trouble with the form you can try using an absolute path, if you aren't already.

Declare a JavaScript variable that will hold place for php variable

I have an app for making questionnaires. Users have index.php page where they create the questions and choose minimum number of answers, then they have process.php page where they can enter their answers or add more answers.
PROBLEM: When user clicks add more button, it creates textarea of the particular question but with the wrong name. The add more button should add a textarea and change its name according to the minimum of the defined textareas. So if you for ex. have 4 defined textareas in question2, the next textareas should be like odg25, odg26, odg27, odg28 etc...
The problem is in variable $k (process.php) - because it is not defined in addmore function, but I don't know how to pass somehow in this part of code to make it happen.
THIS IS THE TESTING LINK
INDEX.PHP
<input id="btntxt" type="submit" value="TEXT" onclick="addtxt();" /><br/><br/>
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
PROCESS.PHP
<script type="text/javascript">
<?php $chars = $_POST['chars']; ?>
function addmore(index) {
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + //WHAT SHOULD I ADD HERE???;
textarea.rows = 3;
textarea.setAttribute('maxlength',<?php echo $chars ?>);
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
<body>
<?php
$bla = "";
$pitanje = $_POST['question'];
$length = count($_POST['question']);
$req = $_POST['req'];
$requiem = '';
$min = $_POST['min'];
$area = array("","","","","","","","","","","","","","","");
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
if(($min[$j])!="") {
for($k=1;$k<=$min[$j];$k++) {
$area[$j] .= '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea><br/>';}}
if(($min[$j])=="") {
$area[$j] = '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea>';}
$addmore = '<input type="button" name="more" value="Add more" onClick="addmore('.$j.');">';
$bla .= $j.') '.$pitanje[$j].'<br/>'.$area[$j].'<div id="inner'.$j.'"></div>'.$addmore.'<br/>';}}
echo $bla;
?>
FNCS.JS
var n = 1;
function addtxt() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var required = document.createElement("input");
required.type = "checkbox";
required.name = "req[" + n + "]";
var minimum = document.createElement("input");
minimum.type = "text";
minimum.name = "min[" + n + "]";
var div = document.createElement("div");
div.innerHTML = n + ". Question: " + "<br />" + textarea.outerHTML + "<br />" + "Required: " + required.outerHTML + "<br />" + "Min: " + minimum.outerHTML + "<br /><hr/><br/>";
document.getElementById("brain1").appendChild(div);
n++;
}
I did the same kind of dev.
I had a globalized counter (cpt) in the javascript is incremented by 1 each duplication
My variables were duplicated like this id = "foo_" + cpt.
I added a hidden field for the counter <input type="hidden" id = "cpt"> and its value was changed for each replication.
Php side, I recovered the counter and then a loop to iterate through all the duplicate fields.
// For example
$cpt = $_POST['cpt'];
for ($i = 1; $i <= $cpt; $i++) {
$foo[$i] = $_POST['foo_' . $i];
}
I hope it will help.
You're mixing JavaScript and PHP. PHP is doing some part of the question generation and then JavaScript has to pick up where it left off.
The problem with that approach is that you'll find you end up duplicating a lot of functionality.
The answer the quesiton WHAT SHOULD I ADD HERE??? is "odg" + $j + $k
If instead you start by doing:
var questions = <?php echo json_encode($_POST["question"]);?>;
You now have all your question data available in JavaScript. You can move the for loop from PHP to JavaScript and have j and k there.
What you're going to have to do is make $k able to be passed into process.php.
That is accomplished with something like this:
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input id="numRows" type="hidden" name="numRows" value="1"/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
notice I've added a new <input> element with the name "numRows" which will be passed via POST to process.php. I've given it an arbitrary default value of 1, you can set this however you wish.
Now, when a user clicks the "add more" button, within fncs.js do this:
document.getElementById("numRows").value++;
and finally, in your process.php you need to read in the value of this, as $k:
<?php $k = isset($_POST['numRows']) ? urldecode($_POST['numRows']) : 1; ?>
within process.php you may do as you wish, then, with that value $k.
You need to store last text area value in hidden variable and always increment that
first step: At start set value of hidden variable and your counter
'n' same
second step : at each step where you are adding new text area ,
overwrite the hidden value by new counter value of text area
Remember Textarea counter should be always fetched from hidden value
I think this may help you to solve your problem

Change form input value with javascript

I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.

Firing a function on click

I have addBanner() function shown below which is invoked every time I click addBanner button. This adds a input field and fires the ausu auto-suggestion jQuery script.
When I click addBanner() Button I get a input field and auto-suggestion works fine. Suppose I click addBanner() button again it adds another empty Input Field and auto-suggestion works fine for that too as the auto-suggest function is fired every time I click addBanner Function. But, if I want to edit the first Input Field which I had added there's conflict. Please tell me how to get the control back to the first input field.
var bnrc = 1;
var bnrl = 5;
function addBanner(divName){
if (bnrc == bnrl) {
alert("You have reached the limit of adding " + bnrc + " Banner companies.");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "banner_sugg";
newdiv.innerHTML = (bnrc + 1) + ". <input type='text' value='' name='banner[]' id='banner" + (bnrc + 1) + "' autocomplete='off' /> <input type='hidden' value='' name='bannerID[]' id='bannerID" + (bnrc + 1) + "' autocomplete='off' />";
document.getElementById(divName).appendChild(newdiv);
bnrc++;
}
$.fn.autosugguest({
className: 'banner_sugg',
methodType: 'POST',
minChars: 1,
rtnIDs: true,
dataFile: 'e_data.php'
});
}
Did you spell suggest wrong on purpose? I'm spelling it correctly below so you may need to alter it.
You are currently (re)calling $.fn.autosuggest({}) every time you add a new item, which may be breaking the previous items.
Try:
$(newDiv).autosuggest({})
So it only adds autosuggest functionality to the new div. And you should move the code above into the section where you create the newDiv as it's even being called on error.

Categories

Resources