Declare a JavaScript variable that will hold place for php variable - javascript

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

Related

Handle apostrophe in input field

I have some js that adds an input field for a user:
var user = "O'Conner, John"
b.innerHTML += "<input type='hidden' value='" + user + "'>";
When its inserted it looks like this:
<input type="hidden" value="O" Conner, John'>
How do I amend this so it outputs like this:
<input type="hidden" value="O'Conner, John">
I need the value to show the full name with the apostrophe. How can I get this to work?
You can escape the value first by replacing it with HTML entities.
As for ' - It can either be ’ or ‘
var user = "O'Conner, John";
user = user.replace("'", "‘");
document.getElementById("container").innerHTML += "<input type='text' value='" + user + "'>";
<div id="container"></div>
There is also another thread that already answers this question.
When you create an element with JavaScript, you can pass the value to the input without any issue. Please check the below example:
var user = "O'Conner, John"
var b = document.getElementById("b")
var input = document.createElement("input")
input.type = "text"
input.value = user;
b.appendChild(input)
<body id="b"></body>

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>

HTML Form wont create new entries

I am trying to create a basic form fill, where you can add a season or new entries and that will post to a databse and I can't seem to figure it out for the life of me. When I run it what I get is that the new seasons "Add more Episodes" buttons dont work and that the title for seasons are in the wrong place.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// create a variable
$title=$_POST['Title'];
$seasonNum=$_POST['SeasonNum'];
//Execute the query
$connect = mysqli_connect('localhost','root','123','mydatabase');
$sql = "INSERT INTO $title(SeasonNum) $SeasonNum(myInputs[])";
mysqli_query($connect, $sql);
if(!$connect) {
die 'Failed to connect because ' . mysqli_connect_errno();
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<span id="responce"></span>
<h2>Season 1</h2>
<form method="post" action="">
<div id="dynamicInput">
Entry 1<br><input type="text" name="myInputs[]">
</div>
<br>
<input type="button" value="Add Another Episode"onClick="addInput('dynamicInput');">
<input type="button" value="Add Another Season" onClick="addSeason('dynamicSeason');">
<div id= "dynamicSeason">
</div>
<input type="submit" value="Add Show">
</form>
<script src="script.js" charset="utf-8"></script>
</body>
</html>
JavaScript file (script.js)
var counter = 1;
var limit = 3;
var EpisodeAdd = 2;
x=1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + "<br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function addSeason(divName){
i=1;
x++;
var h1 = document.createElement("h1");
var h1Text = document.createTextNode("Season " + x);
h1.appendChild(h1Text);
document.body.appendChild(h1)
while(i>0){
var newdiv = document.createElement('div');
newdiv.innerHTML = "h1Text Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'><br><input type='button' value='Add Another Episode' onClick='addInput('Dynamic'EpisodeAdd);'>";
document.getElementById(divName).appendChild(newdiv);
i--;
EpisodeAdd++;
}
counter++;
}
First problem: You're missing a comma here. Notice the change. Also, the `myInputs[]' thing doesn't make sense. Not sure what you're doing there.
mysqli_query($connect, "INSERT INTO " . $title(SeasonNum) .
$SeasonNum(myInputs[]));
Also, you've got a lot of stuff out of order. You can't execute the insert query at the top of the script when it first loads. It should only do that when you submit the form. So wrap it in an if statement:
if($_POST['submit']){
$title=$_POST['Title'];
$seasonNum=$_POST['SeasonNum'];
mysqli_query($connect"INSERT INTO $title(SeasonNum)
$SeasonNum(myInputs[]);
$connect=mysqli_connect('localhost','root','123','mydatabase');
if(mysqli_connect_errno($connect))
{
echo 'Failed to connect';
}
}
There might be other problems too but until you get the basics sorted out, I don't know what they are. I'd suggest getting things in order and then posting a new question as you get closer to the solutions.

JS to add form fields with a button

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>

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.

Categories

Resources