Updating multiple field with javascript - 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 :

Related

adding multiple inputfield using javascript in php not working

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" />

Dropdown populated with database data that adds on button click

I am confused how to populate my dropdown that adds on button click with database values . I used jQuery to do the adding function of dropdown on button click. but it seems like i cant populate the options of the select tag inside my jQuery with database values. Please help me out...
This is my php page
<?php include("connect.php");
$smt = $conn->prepare('select CompanyName From Company');
$smt->execute();
$data = $smt->fetchAll();
?>
<div class="form-group" id='TextBoxesGroup'>
<label for="layer" class="col-sm-3 control-label">Layer</label>
<div id="TextBoxDiv1" class="col-sm-6">
<select class="form-control" id='textbox1' name="company" placeholder="Company" >
<?php foreach ($data as $row): ?>
<option><?=$row["CompanyName"]?></option>
<?php endforeach ?>
</select>
</div><hr/>
</div>
<div class="form-group" >
<div class="col-md-9 text-right">
<input type='button' class="btn btn-default" value='Add +' id='addButton'>
</div>
</div>
The jQuery code used to add dropdown on button click is:
EDIT:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 Layers allowed");
return false;
}
var companies = [<?php echo "'".join("','",$data)."'";?>];
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div class="form-group" id="TextBoxesGroup"><label class="col-sm-3 control-label">Layer '+ counter + ' : </label>' +' <div id="TextBoxDiv1" class="col-sm-6"><select class="form-control" name="textbox' + counter + '" id="textbox' + counter + '" name="company" placeholder="Company">');
$.each(companies, function(key, value){
newTextBoxDiv.append('<option>'+value+'</option>');
});
newTextBoxDiv.append('</select> </div></div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});
</script>
But the output shows like this:
Thanks
Well, you need to echo out the value of $row['companyName'] (the one inside your foreach loop)
Another implementation would be... say you have an array of values in your PHP.
$data = array("company A", "company B", "company C");
And the javascript...
<script>
var companies = [ <?php echo "'". join("','", $data) . "'";?> ];
//This generates : ['company A', 'company B', 'company c'];
function insertOptions()
{
$.each(companies, function(key, value){
$("#IDofSelectTag").append("<option>"+value+"</option>");
});
}
</script>

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 } ?>

can i insert string after "this" inside onclick in Javascript?

newbie asking here.
i have an ordered list of multi dimensional array
$blok = array
(
array("B","X","X",3,4,5,"X",7,8,9,10),
array("G",1,2,3,4,5,6,7,8,9,10),
array("L",1,2,3,4,5,6,7,8,9,10),
array("Q",1,2,3,4,5,6,7,8,9,10)
);
and then i echo each and every array value into separate div :
*already figured it out how to echo them and insert them into div id.
my question is : can i insert string after "this" inside onclick ?
<div class="span4"><div class="table1" style="float:left; background-color:magenta;" id= "'. //ARRAY VALUE// .'" onclick="select(this,"B");" >
<div class="span4"><div class="table1" style="float:left; background-color:blue;" id= "'. //ARRAY VALUE// .'" onclick="select(this,"Q");" >
my goal is to input the div id (the array value) and the string into my database using input type=hidden after onclick
<input type="hidden" id="type" name="type" value="" />
<input type="hidden" id="table" name="table" value="" />
any help is appreciated, i'm drawing a blank here.
btw this is my javascript :
var i=0; document.getElementById("table").value=""; function select(id , tipe){
if($(id).attr('class')=="table2"){
$(id).attr('class','table1');
var m=document.getElementById("table").value.split(",");
var removeItem = $(id).attr('id');;
var n = jQuery.grep(m, function(value) {
return value != removeItem;
});
document.getElementById("table").value=n;
if(n.length==0){i=0;}
}else{
$(id).attr('class','table2');
if(i==0){
document.getElementById("table").value+=$(id).attr('id');
i=1;
}else{
var j=document.getElementById("table").value.split(",");
if(jQuery.inArray($(id).attr('id'), j)==-1) {
document.getElementById("table").value+=","+$(id).attr('id');
}
}
}
var type=document.getElementById('type');
type.value=tipe }
edit : i forgot to mention i'm using concatenation assignment like this :
$number =' <div class="table1" style="float:left; background-color:magenta;" id= "'. $blok[$row][$col] .'" onclick="select(this,"B");" > ';
$number .= $blok[$row][$col]; //echo the array value to display the table number
$number .=' </div> ';
so to display those div with ARRAY VALUE as div id and text to display
i only wrote :
echo $number;
Wrap the second argument into a single quotes:
.. onclick="select(this,'B');" ...
for your php code:
.'" onclick="select(this,'."'B'".');" > ';

updating database field when a checkbox for an element is clicked

here is what i have so far :sql that gets data from the database, the data is passed through a loop and then displayed with the html code
$sql = "SELECT items_available.title,
items_available.item_number,
items_available.subtitle,
items_available.image_name,
users.username
FROM items_available
INNER JOIN users ON items_available.owner_id = users.user_id
WHERE items_available.status ='pending'
LIMIT $query_limit ;";
$query = mysql_query($sql);
while ($dbData = mysql_fetch_assoc($query)) {
$item_id = $dbData['item_number'];
$sel_title = $dbData ['title'];
$sel_Image = $dbData['image_name'];
$sel_subtitle = $dbData['subtitle'];
$sel_owner = $dbData['username'];
echo "<span style='display:inline-block;width:185px;margin:4px;'>
<a href='#'>
<img src='upload/$sel_Image' style='width:180px; height:160px;' />
<h5 style='display:inline;'>$sel_title </h5><br>
<h7 style='display:inline;'> $sel_subtitle</h7><br>
<h6 style='display:inline;'>Posted by $sel_owner</h6>
</a>|
<div style= \"display:inline-block;\">
<input type=\"checkbox\" id=\"check\" name='item_ids[]' value='1' />
</div>
</span>";
}/
the checkbox below the block of codes should grab the ids of each element so an update to the database is possible.Hope my description is clear enough to be aided
you did nt give any specfic so it is like a guide for what u asking
you need to create a form here with a hidden field
like
<div style= \"display:inline-block;\">
<form method=\"post\">
<input type=\"hidden\" name=\"value\" =". $item_id.">
<input type=\"checkbox\" name=\"update\" value = '1' />
</form>
</div>
php for that ll look like
if (isset($_REQUEST['value']))
{
//update after validation
}
P.S $_REQUEST Deals with both for GET or POST method
it actually depends what you want
You can make the VALUE of the checkbox into the id you want to get back in the $_POST['item_ids'] array.
<div style= \"display:inline-block;\"> ";
echo '<input type="checkbox" id="check" name="item_ids[]" value="' . $item_id . '" />';
echo "</div>
Now in your PHP code you can process them like this, remember checkboxes are only returned in the $_POST/$_GET array if they are actually checked.
I am assuming $_POST.
if ( isset($_POST['item_ids']) ) {
foreach ( $_POST['item_ids'] as $item_id ) {
// do whatever you want to with this information
}
}

Categories