I have this block of code:
<div id='mydiv'>
<?php
for($i = 0; $i < count($array); $i++)
{
print"<span>";
print"<input type='button' value='+' />";
print"<input type='button' value='-' />";
print"<span>counter_value</span>";
print"</span>";
print"<br />";
}
?>
</div>
The idea is that you click on one of the buttons and the value in the inner <span> tag increments or decrements by 1. The HTML/PHP itself displays the above perfectly well and displays the elements. However, my issue is that $array can have an arbitrary number of elements. If there are (for example) five outer <span> tags, I want to know which one of the buttons has been clicked .(This would be done using jQuery) Because the HTML is generated in a for-loop I'm reluctant to give the elements IDs.
In the jQuery I think I will need something like this:
var div = $('#mydiv');
div.on("click", "a", function(){
//Determine the <span> tag where the button was clicked.
//Get the counter value from the inner <span> tag within this <span> tag.
//Determine which button was clicked.
//Add/subtract one from value and update value in inner <span> tag.
});
I hope I've made the issue clear enough to be understandable. Any help would be appreciated.
I've just given the button elements class names to determine whether to add or subtract
<?php
$array = array_fill(0,2,'Hello World');
?>
<div id='mydiv'>
<?php
for($i = 0; $i < count($array); $i++)
{
print"<span>";
print"<input type='button' value='+' class='plus' />";
print"<input type='button' value='-' class='minus' />";
print"<span class='counter_value'>0</span>";
print"</span>";
print"<br />";
}
?>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$('#mydiv').on('click','input[type="button"]',function(){
var el = $(this).parent('span').find('.counter_value');
if($(this).hasClass('plus')){
$(el).html(parseInt($(el).text()) + 1);
}else{
$(el).html(parseInt($(el).text()) - 1);
}
});
</script>
$("#mydiv :button").click(function() {
var span = $(this).siblings("span");
var direction = $(this).val() == '+' ? +1 : -1;
span.text(function(i, oldval) {
return parseInt(oldval, 10) + direction;
});
});
Related
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>
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.
A Product List is created using the PHP code each product having its own checkbox, I have used the Java Script code to get values of all the selected checkboxes now i need to call an other PHP page which will receive this string data and populate all the selected products list. Can you please tell me the way i can use to send data to another php page using javascript POST method.
Code used to create the product list and get value of selected checkboxes is as follows :
<?php
$cnt=0;
$rslt = mysqli_query($conn,"SELECT Icode,Name,Size,Style FROM productinfo");
if(!$rslt)
{
die(mysqli_error($conn));
}
else
{
echo " <table width='100%'>";
while($row = mysqli_fetch_assoc($rslt))
{
if($cnt==0)
{
echo "<tr>";
}
echo "<td width='30%'>
<div class='card'>
<img src='upload/"."download.jpg"."' alt='Avatar' style='width:100px' >
<div class='container'>
<h4><b>".$row['Name']." <input type='checkbox' name='prodchklist' value=".$row['Icode']." '/> </b></h4>
<p>".$row['Size']."</p>
<p>".$row['Icode']."</p>
</div>
";
?>
</div>
<?php
echo "</td>";
if($cnt==2)
{
$cnt=0;
echo "</tr>";
}
else
$cnt = $cnt + 1;
}
}
echo "</table>";
?>
</div>
<button id="SendInquiry" style="display: block;">Send Inquiry</button>
<script type='text/javascript'>
$(document).ready(function(){
$('#SendInquiry').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0)
{
var resultstring = result.length +"checkboxes are checked";
result.each(function(){
resultstring+=$(this).val();
}
);
$('#divrslt').html(resultstring);
}
else
{
$('#divrslt').html("nothing checked");
}
});
});
</script>
I don't know your reason to use javascript for collecting checkbox values and post it to another PHP page. You can achive what you want without javascript:
Wrap you checkboxes inside a form, set its action to second page, and don't forget to set its method to POST, eg:
<form action="second.php" method="post">
</form>
Put [] at the end of checkbox name to make it array that can send multiple values with one name, eg:
<input type="checkbox" name="prodchklist[]" value="item1">
<input type="checkbox" name="prodchklist[]" value="item2">
<input type="checkbox" name="prodchklist[]" value="item3">
But, if you really want to use javascript to call the second page, for example by using ajax, do this:
Store the selected values in an array, instead of appending each values in one variable.
// add this, to store the data you want to post
var data = {
prodchklist: []
};
var result = $('input[type="checkbox"]:checked');
if (result.length > 0)
{
var resultstring = result.length + " checkboxes are checked";
result.each(function(){
resultstring += $(this).val();
}
// add this
data.prodchklist.push($(this).val());
}
Then during ajax call:
$.post('second.php', data, function(response) {
....
});
In your second PHP file, just retrieve it as usual, eg:
$selectedProducts = $_POST['prodchklist'];
This works for both approach (without javascript and with ajax).
$selectedProducts will be an array instead of simple string value. Just iterate the array to use the values, eg:
foreach ($selectedProducts as $product) {
echo $product;
}
I've got a click event that is prepending a paragraph tag to an element twice and I'm not understanding why. Can anyone give me a reason?
jQuery
function select_menu(){
var select = $(".select");
var option_menu = $(".option-menu");
var option = $(".option");
select.on("click", function(){
$(this).find(option_menu).toggle();
select = $(this);
$(this).find(option_menu).each(function(){
$(".current").hide();
if($(this).hasClass("current")){
$(this).removeClass("current");
}
else{
$(this).show().addClass("current");
}
})
})
option.on("click", function(){
select.children("p").remove();
var value = $(this).text();
select.prepend("<p><input type='hidden' name='center' id='center' value='" +value +"' />" +value +"<p>");
})
$(document).on("click", function(ev){
if($(ev.target).closest(".select").length === 0){
$(".current").hide().removeClass("current");
}
})
}
Here's the area where the script prepends the paragraph tag to.
HTML
<fieldset for="center">
<label>Center:</label>
<div class="select" name="center_menu" id="center_menu">
<div class="arrow"></div>
<div class="option-menu">
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
global $center_name;
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'>" .$center_name ."</div>";
}
?>
</div>
</div>
</fieldset>
In your code:
select.prepend("<p><input type='hidden' name='center' id='center' value='" +value +"' />" +value +"<p>");
you open and close the paragraph tag the same way. There should be a closing tag.
The page recognizes it like two separate paragraph tags and closes them automatically. Probably this will fix your issue.
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