adding multiple inputfield using javascript in php not working - javascript

i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance

As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>

In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />

Related

Generate <div> section dynamically with a button in PHP/Javascript?

Hi guys I have a code that I want is inside a div and that I would like to generate 1 by 1 when the button 'Add Section' is clicked. Here's my code
surveycontent.php with javascript code
<div id="sform" class="tab-pane fade">
<br>
<div class="col-md-12">
<div class="col-md-10" id="sections">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">Section 1</div>
<div class="panel-body">
<b>Number of Questions: </b>
<span id="ctr_num"> <input id="q_num" class="form-control" style="width:50px;" name="q_num" size="2" placeholder="#"/></span>
<br>
<b>Select Category</b>
<select class="form-control" style="width: 150px;" id="categorydd" name="catdd" onChange="change_category()">
<option>-Please Select One-</option>
<?php
$query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID IS NULL");
while($row=mysqli_fetch_array($query)) {
?>
<option value="<?php echo $row["category_id"]; ?>"><?php echo $row["categoryname"]; ?></option>
<?php
}
?>
</select><br>
<b>Select Subcategory</b>
<div id="subcategory">
<select class="form-control" style="width: 150px;">
<option>-Please Select One-</option>
</select><br/>
</div>
<p hidden>Select Questions</p>
</br>
<div id="question">
</div> <br/>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="col-md-2">
<input type="submit" name="addsection" class="btn btn-default" value="Add Section" id="addsection" />
</div>
</div>
<script>
function change_category()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?category="+document.getElementById("categorydd").value,false);
xmlhttp.send(null);
document.getElementById("subcategory").innerHTML=xmlhttp.responseText;
if(document.getElementById("categorydd").value=="Select")
{
document.getElementById("question").innerHTML="<select><option>Select</option></select>";
}
//alert(document.getElementById("categorydd").value);
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?main=1&subcategory="+document.getElementById("categorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
javascript code for add section button
<script>
$(document).ready(function(){
var ctr = 0;
$("#addsection").click(function(){
var section = document.getElementById("sections").innerHTML;
$("#sections").append(section);
ctr++;
});
});
</script>
I assume this is wrong, because this code i have atm will just make it bug like if I generate 1 section, and choose a data on the dropdowns for the added section, it will do the same thing to the first section, like it copies what you move for one section. This is a creation survey system and this is the part of adding sections.
The code behind those category, subcategory, question dropdowns.
ajax.php
if($category!=""){
$query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID =$category ");
echo "<select id='subcategorydd' class='form-control' style='width:150px;' name='subcatdd' onchange='load_questions()' >";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[category_id]'>"; echo $row["categoryname"]; echo "</option>";
}
echo "</select>";
}
// for loading ques under Category already
if($question !="" && $cnt!="" && $addQues!="yes" && $main == 1){
$i = 0;
for( $i = 1; $i <= $cnt; $i++ ){
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "<form>
<b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
<select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
<option selected>Select";
while($row=mysqli_fetch_array($query)){
echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
}
echo "
</select>
</form>
<div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues_Cat();'>Add Question</a> | ";
echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}
// for loading ques under SUBCATEGORY
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "
<form>
<b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
<select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
<option selected>Select";
while($row=mysqli_fetch_array($query))
{
echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
}
echo "
</select>
</form>
<div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
<br />";
}
echo "<div id='insertQuesHere".$i."'></div> ";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a> | ";
echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}
I think the HTML markup should perhaps be more like this. If you indent your code correctly as you go you will often find it is much easier to find issues.
There are several sites on the interwebs that could help with the code indentation - for example and you can validate your pages using other services, such as the W3C Markup Validator
<div id='sform' class='tab-pane fade'>
<br />
<div class='col-md-12'>
<div class='col-md-10' id='sections'>
<div class='panel-group'>
<div class='panel panel-default'>
<div class='panel-heading'>Section 1</div>
<div class='panel-body'>
<b>Number of Questions: </b>
<span id='ctr_num'> <input id='q_num' class='form-control' style='width:50px;' name='q_num' size='2' placeholder='#'/></span>
<br />
<b>Select Category</b>
<select class='form-control' style='width: 150px;' id='categorydd' name='catdd' onChange='change_category()'>
<option>-Please Select One-</option>
<?php
$query=mysqli_query($con, 'SELECT `category_id`, `categoryname` FROM `category` WHERE `ParentCategoryID` IS NULL');
while( $row=mysqli_fetch_array($query) ) {
?>
<option value='<?php echo $row['category_id']; ?>'><?php echo $row['categoryname']; ?></option>
<?php
}
?>
</select>
<br />
<b>Select Subcategory</b>
<div id='subcategory'>
<select class='form-control' style='width: 150px;'>
<option>-Please Select One-</option>
</select>
<br />
</div>
<p hidden>Select Questions</p>
<br />
<div id='question'>
</div>
<br />
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class='col-md-2'>
<input type='submit' name='addsection' class='btn btn-default' value='Add Section' id='addsection' />
</div>
I don't know if this will help or not or indeed whether I have understood the problem correctly ( that of effectively cloning the contents of the section when the button is clicked? )
The following clones the entire section ( there are no ID attributes to worry about but there will be duplicate names ) so a little more work would be invloved to make the new clone unique in the DOM and to change the section title / section number.
Copy and run the code - as posted - and see if it does more or less what you were trying to do. The ajax code does not perform all the tasks in the original code - like setting the contents of the question
<?php
session_start();
/* to emulate the ajax request that is sent by change_category() */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['action'] ) && $_POST['action']=='changecat' ){
ob_clean();
for( $i=0; $i < 10; $i++ )echo "<option value='$i'>Choice - $i";
exit();
}
}
?>
<!doctype html>
<html>
<head>
<title>Cloning a section of the HTML page</title>
<style></style>
<script>
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ){
/*
The callback takes 3 arguments
------------------------------
r=xhr.response
o=options ( as supplied to ajax function )
h=response headers
*/
c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
}
};
var params=[];
for( var n in p )params.push(n+'='+p[n]);
switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
function change_category(evt){
var el=evt.target;
console.log('ajax function to get contents of dropdown - '+el.value+' & append returned data to subcategory?' );
var method='post';
var url=location.href;
var params={
action:'changecat'
};
var callback=function(r,o,h){
var col=el.parentNode.querySelectorAll('select.subcategory');
if( col.length==1 )col[0].innerHTML=r;
col=el.parentNode.querySelectorAll('div.question');
if( col.length==1 )col[0].innerHTML='Some question - relating to Select:'+el.tagName+', Name:'+el.name+', Option:'+el.value+', chose from the database, goes here I believe?';
}.bind( this );
var options={};
ajax.call( this, method, url, params, callback, options );
}
function clone_section(e){
e.preventDefault();
var parent=document.getElementById('clone-parent');
var col=parent.querySelectorAll('div.clone-section');
var section=col[ col.length-1 ];
var clone=section.cloneNode( true );
/* change the heading */
var heading=clone.querySelectorAll('div.panel-heading')[0];
var regex=/(\d+)/gi;
var matches=heading.innerHTML.match( regex );
var i=parseInt( matches[0] );
heading.innerHTML=heading.innerHTML.replace( i, i + 1 );
/* make changes to the various cloned elements */
var q_num=clone.querySelectorAll('input[name^="q_num_"]')[0];
var matches=q_num.name.match( regex );
var i=parseInt( matches[0] );
q_num.name = q_num.name.replace(i,i+1);
q_num.value='';
var cat=clone.querySelectorAll('select[name^="catdd_"]')[0];
var matches=cat.name.match( regex );
var i=parseInt( matches[0] );
cat.name=cat.name.replace(i,i+1);
cat.value='';
var subcat=clone.querySelectorAll('select[name^="subcategory_"]')[0];
var matches=subcat.name.match( regex );
var i=parseInt( matches[0] );
subcat.name=subcat.name.replace(i,i+1);
subcat.value='';
parent.appendChild( clone );
}
function bindEvents(){
var bttn=document.getElementById('addsection');
bttn.addEventListener( 'click', clone_section.bind( bttn ), false );
}
document.addEventListener('DOMContentLoaded',bindEvents,false);
</script>
</head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !isset( $_POST['action'] ) ){
print_r( $_POST );
}
?>
<form name='geronimo' method='post'>
<!--// markup from question //-->
<div id='sform' class='tab-pane fade'>
<br />
<div class='col-md-12' id='clone-parent'>
<!-- it is the following portion of HTML that is to be replicated? -->
<div class='col-md-10 clone-section'><!-- removed ID, added new class -->
<div class='panel-group'>
<div class='panel panel-default'>
<div class='panel-heading'>Section 1</div><!-- this needs to change progammatically or via CSS-->
<div class='panel-body'>
<b>Number of Questions: </b>
<span class='ctr_num'> <input class='form-control' style='width:50px;' name='q_num_1' size='2' placeholder='#' /></span>
<br />
<b>Select Category</b>
<select class='form-control' style='width: 150px;' name='catdd_1' onchange='change_category( event )'>
<!-- PHP removed for example - replaced with dummy data -->
<option>-Please Select One-
<option value='a'>A
<option value='b'>B
<option value='c'>C
<option value='d'>D
<option value='e'>E
</select>
<br />
<b>Select Subcategory</b>
<div class='subcategory'>
<select name='subcategory_1' class='form-control subcategory' style='width: 150px;'>
<option>-Please Select One-</option>
</select>
<br />
</div>
<p>Select Questions</p>
<br />
<div class='question'></div><!-- assigned as a class rather than id - can be targeted using querySelectorAll etc -->
<br />
</div>
</div>
</div>
</div>
<!-- end replicated code -->
</div>
</div>
<hr>
<div class='col-md-2'><!-- add new section button - uses javascript:onclick -->
<input type='button' name='addsection' class='btn btn-default' value='Add Section' id='addsection' />
</div>
<input type='submit' /><!-- to actually submit the form -->
<!--// end markup from question //-->
</form>
</body>
</html>

Using AJAX to update a dynamic webpage

I made a webpage that consists of projects, where each project consists of a list of files. All of this information is acquired from a MySQL database. I've implemented a feature that allows users to comment on each file and reply to each other's comments. I have a php function called "place comments" which recursively places comments for each file shown below.
This is executed for every file and every file is displaced similarly using a while loop and some statements that echo html code.
However, the issue I'm having is using AJAX to post comments without the page refreshing. Since each file id is different, I would have to update every selector with a particular file id and run placeComments again for every file.
However I'm not sure how to accomplish this. I'm able to update my database through AJAX everytime I submit a comment.
I know you can do something like the following and it will update any selector with the id "id":
$(document).ready(function() {
$.get('comments.php', function (data) {
$('#id').html(data);
});
});
But I'm not sure how I can do this iteratively for every file id where each file id is a php variable?
Is there a way I can communicate with JS through PHP so it updates comments
for all file ids? If so, how?
I realized that this is a terrible design, but I'd like to do this without starting my project from scratch.
Place comments function:
function placeComments($mysqli, $parentId, $fileId) {
$sql = "SELECT * FROM Comments WHERE parent = $parentId AND file = $fileId ORDER BY UNIX_TIMESTAMP(date) ASC";
$comments = $mysqli->query($sql);
while($comment = $comments->fetch_assoc())
{
echo '
<ul class="comments">
<li class="clearfix">
<div class="post-comments">
<p class="meta"> '. $comment['date'] .' '. $comment['username'] .' says : <i class="pull-right">
<p>'
.
$comment['content']
.
'</i></p><br><br>';
echo '<div class = "col-sm-12 reply panel-group">';
echo '<div class="panel panel-default">';
echo '<p><a data-toggle="collapse" href="#'. $comment[
'file'] . '-' . $comment['id'] . '"> Reply </a></p>';
echo '<div id="'. $comment['file'] . '-' . $comment['id'] .'" class="panel-collapse collapse">';
echo '<div class="panel-body">';
if(isset($_POST['submitComment-' . $comment['file'] . '-' . $comment['id']]))
{
$user = $_POST['username'];
$content = $_POST['content'];
$fileId = $_POST['id'];
$parent = $_POST['parent'];
$date = date('Y-m-d H:i:s', time());
filterComment($mysqli, $fileId, $user, $parent, $content, $date);
}
echo '<form method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10 form">
<h5><b> Name: <b></h5>
</div>
<div class="col-sm-10 form">
<textarea class="form-control" name="username" id="username" rows="1"></textarea>
</div>
<div class="col-sm-10 form">
<h5><b> Reply: <b></h5>
</div>
<div class="col-sm-10 form">
<textarea class="form-control" name="content" id="content" rows="3"></textarea>
</div>
<div>
<input class = "form-control" type = "hidden" value = '. $comment['file'] . ' name = "id" id = "id" />
</div>
<div>
<input class = "form-control" type = "hidden" value = '. $comment['id'] . ' name = "parent" id = "parent" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10 form">
<button class="btn btn-success btn-circle text-uppercase" type="submit" id="submitComment" name = "submitComment-'. $comment['file'] .'-' . $comment['id'] . '"><span class="glyphicon glyphicon-send"></span> Reply </button>
</div>
</div>
</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div><br><br>';
placeComments($mysqli, $comment['id'], $comment['file']);
echo '</div>';
echo '</li>';
echo '</ul>';
}
$comments->free();
}

Populate multiple form fields from foreach statement

I'm trying to populate multiple form fields from a generated button in a foreach statement. I don't have a vast knowledge of JS so I don't know if I'm just not thinking of a certain function or not.
I have the following code and I'm able to get title to populate in the form but I have no clue where to start for populating content as well based of the same button. ex: one button will load a specific title and content value while another edit button will load another specific title and content value.
//Announcement table select
$sql = "SELECT * FROM `announcements` ORDER BY `startDate` DESC"; //I want to see all existing announcements from database
$announcement = $dbConnect->query($sql);//execute query
$a = 0;
?>
<script type="text/javascript">
function changeText(title, content){
document.getElementById('title').value = title.id;
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].');" value="Edit">';
echo '<p id="'.$y[$a].'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
</div>
</div>
</div> <!--m4 ends here-->
<div class="col m8 s8"> <!--m8 starts here-->
<div class="titleboxmargin grey" style="width:100%;">
<div class="bar yellow"></div>
<img class="boxicon" src="../images/announcementsicon.svg">
<h3 class="title">Announcements</h3>
</div>
<div class="col yellow-light"> <!--Announcement Form Starts-->
<form action="includes/postAnnouncement.php" method="post">
<ul class="yellow-form">
<li class="textfield-container">
<label for="text" class="textlabelblack">Title:</label>
<input id="title" name= "title" type="text" placeholder="Title of My Announcement">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Start Date:</label>
<input type="date" id="startDate" name="startDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">End Date:</label>
<input type="date" id="endDate" name="endDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Announcement:</label>
<textarea id="content" name="content" rows="7"></textarea>
</li>
<li class="textfield-container">
<div class="leftsidebutton">
<input type="submit" class="button" style="width:auto; padding:5px; border:0;" name="register" value="Submit the form"/><!--Action: Attempts to Redirect to postAnnouncement.php-->
</div>
</li>
</ul>
</form>
The following code works
Edit:
<script type="text/javascript">
function changeText(title, content){
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
document.getElementById('title').value = document.getElementById(title).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$tile = $row["announcementID"] * 2;
$cont = $row["announcementID"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$tile.'" data-content="'.$row["title"].'" type=button class=test onclick="changeText(id, '.$cont.');" value="Edit">';
echo '<p id="'.$cont.'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
You could add a second parameter to your onclick handler:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, content){
document.getElementById('title').value = elem.id;
/*
* Here we get the value of the hidden content by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = document.getElementById(content).value;
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].'); startDate('.$y[$a].'); " value="Edit">';
echo '<p style="display:hidden;" id="'.$y[$a].'" ></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
EDIT:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, contentID){
var contentElem = document.getElementById(contentID);
document.getElementById('title').value = elem.getAttribute('data-title');
/*
* Get the value of the hidden content's data attribute by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = contentElem.getAttribute('data-content');
}
</script>
<?php
// Let's get $index as well
foreach ($announcement as $index => $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
// Not sure if I'm escaping quotes correctly on this line:
echo '<input id="title'.$index.'" data-title="'.$x[$a].'" type=button class=test onclick="changeText(this, \"content'.$index.'\"); startDate('.$y[$a].'); " value="Edit">';
// Generate a unique id that we can reference
// and add `data-content` attribute
echo '<p style="display:hidden;" id="content'.$index.'" data-content="'.$y[$a].'"></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
I am not sure what your title and content values are, but I suspect they are not valid HTML element IDs. I think it would be better to avoid using the DOM as a data store and instead create a JSON representation of your announcement table in your script. My PHP is a little rusty, but it should be something similar to:
<script>
var rows = <?php echo json_encode($announcement); ?>;
</script>
Hopefully this will produce something like the following:
var rows = [
{
"title": "Title One",
"content": "Content One"
},
{
"title": "Title Two",
"content": "Content Two"
}
];
This way, our changeText function need only accept a row index as parameter:
function changeText (index) {
document.getElementById('title').value = rows[index].title;
document.getElementById('content').value = rows[index].content;
}
All that is left is to pass the row index where we call changeText:
<?php foreach ($announcement as $index => $row) { ?>
<!-- echo your HTML markup here. -->
<button onclick="changeText(<?php echo $index; ?>);">Edit</button>
<?php } ?>

Updating multiple field with javascript

I have next form :
<?php
echo "<form action=\"test.php\" method=\"post\">";
$rez = mysqli_query($kon, "SELECT * FROM shops");
while($red = mysqli_fetch_assoc($rez)){
$niz = array(
array($red["id"],$red["naam"])
);
echo "<div class=\"col-xs-12 col-sm-12\">
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces();\"/>
</div>
</div>
<div class=\"col-sm-10 col-xs-8\">
Informacije
</div>
</div>
<div class=\"footer\" style=\"position: fixed;bottom: 0;width: 100%;left:0;\">
<span class=\"glyphicon glyphicon-chevron-left\"></span> Niets toevoegen
<button class=\"col-xs-6 col-sm-6 btn btn-danger\" type=\"submit\" name=\"btnNaruci\" id=\"btnNaruci\">
Leg in winkelmand <span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span>
</button>
</div>";
}
echo "</form>";
?>
I want to update this hidden field for every result. I have now 5 results but if i increase quantity, the hidden field get value only if i increase quantity of first result.
I have onChange by the quantity input field and then in javascript i get the value of that field and add it to the value of the hidden field, but the value of the hidden field is changed only for the first result in while loop..
Thanks in advance...
I would need the body of your proces() function to say for sure, but I think you reference your input field by id, all 5 input fields have the same id. Only first gets updated and that's the problem. Either give different ids (by adding count) or reference by class. That would work, however having same id for multiple fields is not a good idea.
Post the body of the function and I can give more detailed help.
Ok, so they do have the same id. You could go by class to update them like this:
var quan = document.getElementById("quan").value;
var hiddenfields = document.getElementsByClassName('hidd');
for (var i = 0; i < hiddenfields.length; ++i) {
var item = hiddenfields[i];
item.value = quan;
}
Or if it's ok tu use JQuery:
var quan = $("#quan").val();
$( ".hidd" ).val(quan);
Based on your comment:
I see. I think simplest would be to do the following:
In your php code add id (concat as string), and add it to the call of your updating function
This might not compile, but gives you the idea:
$i = 1;
while($red = mysqli_fetch_assoc($rez)){
// ...
echo "<div class=\"col-xs-12 col-sm-12\">
// ...
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd".$i."\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan".$i."\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces('quan".$i."', 'txtHidd".$i."');\"/>
</div>
</div>
// ...
</div>";
$i++;
In javascript the updating function would use the parameter
function proces(quanID, hiddenID) {
var quan = document.getElementById(quanID).value;
document.getElementById(hiddenID).value = quan;
}
EDIT AGAIN
I found that the /" at the id fields were in wrong position.
Updated sample code. Basically your html output is supposed to look like this (I didn't include name, as it doesn't matter, now we are only looking at id-s):
...
<input class="hidd" type="hidden" name="xxxxx" id="txtHidd1" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan1" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan1', 'txtHidd1');"/>
</div>
</div>
...
...
<input class="hidd" type="hidden" name="xxxxxx" id="txtHidd2" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan2" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan2', 'txtHidd2');"/>
</div>
</div>
...
Looking at the id-s and the call of the function. If it's like that, the javascript update part will work perfectly.
That is my test.php page
<?php
session_start();
include("config.php");
global $kon;
ob_start();
print_r($_POST["txtHidd"]);
foreach ($_POST["txtHidd"] as $id => $id_prod) {
foreach ($id_prod as $kolicina) {
echo "<br />Id : {$id} and quantity : {$kolicina}<br />";
}
}
ob_flush();
?>
And result tha i get when i hit a post is next :
Array ( [17] => Array ( [kolicina] => ) [18] => Array ( [kolicina] => ) [19] => Array ( [kolicina] => ) [20] => Array ( [kolicina] => ) )
Id : 17 and quantity :
Id : 18 and quantity :
Id : 19 and quantity :
Id : 20 and quantity :

Ajax script breaking at callback

I have this script which works once but I can't seem to replicate it inside the same document.
The JQuery:
$("document").ready(function() {
//This first instance works
if($("#add-menu").length) {
$("#add-menu").change(function() {
var datum = 'shortname=' + $(this).val() + '&table=projects';
$.post('proj_query.php', datum, response);
function response(data) {
var jSON = $.parseJSON(data);
$("label:contains('Title:') + input:first").val(jSON.title);
$("label:contains('Medium:') + input:first").val(jSON.medium);
$("label:contains('Dimmensions:') + input:first").val(jSON.description);
$("label:contains('Work Blurb:') + textarea:first").val(jSON.blurb);
}
});
}
//This one doesn't work
if($("#id-blurb").length) {
$("#id-blurb a").click(function() {
if($("#edit-menu").val().length) {
var datum = 'shortname=' + $("#edit-menu").val() + '&table=projects';
$.post('proj_query.php', datum, responseB);
function responseB(data) {
var jSON = $.parseJSON(data);
$("#id-blurb textarea").val(jSON.blurb);
}
}
});
}
});
When I test by running alerts, I get alerts right up until I add the callback function (the one called 'responseB'). Then it stops generating them. So it seems it's finding the document, and it seems to be accepting the data, but that's about it. After that nothing happens.
proj_query.php looks like this:
<?php
require_once ('../functions/functions.php');
connectDB('../functions/login.php');
require_once("session.php");
if(isset($_POST['shortname'])) {
$shortname = $_POST['shortname'];
$table = $_POST['table'];
$query = "SELECT title, medium, description, blurb FROM $table WHERE shortname='$shortname'";
$result = mysql_query($query);
$results = mysql_fetch_array($result, MYSQL_ASSOC);
print_r(json_encode($results));
}
?>
The HTML is this (but you may not need that):
<div id="change" class="grid_4">
<h3>Edit a Project</h3>
<form method="post" action="index.php" name="editform" onsubmit="return validateEdit(this);">
<input type="hidden" name="edit" value="yes" />
<div class="field_container"><label>Project Name:</label>
<select id="edit-menu" name="shortname">
<option value="">Select a Project...</option>
<?php //For creating the dropdown menu
$query = "SELECT * FROM projects ORDER BY title ASC";
$result = mysql_query($query);
if (!$result) die ("Server says: <br/>Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++) {
$results[] = mysql_fetch_array($result, MYSQL_ASSOC);
$option = $results[$i]['title'];
$value = $results[$i]['shortname'];
echo "<option value=\"$value\">" . $option . "</option>\n";
}
?>
</select>
</div>
<div class="field_container"><label>Title:</label><input type="text" name="title" maxlength="128"/></div>
<div class="field_container"><label>Date:</label><input type="date" name="date" /></div>
<div class="field_container"><label>Medium:</label><input type="text" name="medium" maxlength="256"/></div>
<div class="field_container"><label>Dimmensions:</label><input type="text" name="description" maxlength="64"/></div>
<div class="field_container"><label>Area:</label><input type="text" name="area" maxlength="16"/></div>
<div class="field_container"><label>Video Number:</label><input type="text" name="video" maxlength="64"/></div>
<div class="field_container"><label>New Shortname:</label><input type="text" name="new_shortname" maxlength="16"/></div>
<div class="field_container" id="id-blurb"><label><a title="Click for old content">Work Blurb:</a></label><textarea class="blurb" name="blurb" rows="5" ></textarea></div>
<input class="submit" type="submit" value="Edit Project" />
</form>
</div>
Banging my head on this one...

Categories