Get values of all selected items from user-created select fields - javascript

I have a select field with a add button next to it inside a form. The user will click the add button and create as many extra select fields as he wants and then select an item from each of the select fields. When he submits the form, I want the values of all selected items in an array.
Can any one help please? Thanks.
<?php
session_start();
include ('../conn.inc.php');
?>
<!DOCTYPE>
<html>
<head>
<script>
function addRow(r){
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
var cInp = cRow.getElementsByTagName('input');
for(var i=0;i<cInp.length;i++){
cInp[i].setAttribute('name',cInp[0].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));
root.appendChild(cRow);
}
</script>
</head>
<body>
<form method="get" action="abc()">
<table>
<tr>
<td>
<select name="product_code" id="product_code">
<?php
$sql= mysql_query("select * from product_table where id > 0 order by product_code");
while($row = mysql_fetch_array($sql))
{
$pcode = $row['product_code'];
echo "<option value=\"$row[id]\">".$pcode."</option>";
}
?>
</select>
</td>
<td>
<input name="button" type="button" value="+" onick="addRow(this.parentNode.parentNode)">
</td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
</body>
</html>

It's more simple than what you've done.
You should set the name attribute of all your selects something like productCode[] (with the brackets).
PHP will automatically create you an $_POST['productCode'] variable containing all the values in an array..

Related

Is there a way, to send the value of a button to different pages in PHP?

I am working on project and came across the problem: When i click a button on the e.g. //website/manageuser.php I want the value of the button in the //website/edituser.php
I tried using the <value> tag in a button but failed. I wasn't able to manage to transfer the value through the files.
My manageuser.php looks like this:
After i press the e.g. "Delete" button, i get forwarded to the /deleteuser.php where I want to print the value behind the button. Unfortunatly, it isn't working with a StackOverflow Javascript script.
Image of my /deleteuser.php:
Code of the important part of manageuser.php:
<table>
<tr>
<?php
$query = "select * from users";
$records = mysqli_query($con, $query);
while($data = mysqli_fetch_array($records))
{
?>
<th>
<p/>
<?php
print($data["full_name"]);
?>
<button type="button" value=" <?php print($data['full_name']) ?>" onclick="window.location.href='./edituser.php'">Edit</button>
<button type="button" onclick="window.location.href='./deleteuser.php'"> Delete </button>
</th>
<?php
}
?>
</tr>
</table>
Code of the important part of deleteuser.php:
<!DOCTYPE html>
<html>
<body>
<script>
var str1 = document.getElementById("btn").innerHTML;
var str2 = document.getElementById("btn").value;
document.write("Button text: "+str1);
document.write("<br>Button value: "+str2);
</script>
</body>
</html>
You don't need the value. Just append the value from $data as a query parameter to the URL.
<button type="button" onclick="window.location.href='./deleteuser.php?id=<?php echo $data['id'] ?>"> Delete </button>
Then in deleteuser.php you can use $_GET['id'].

link onclick does not submit form [duplicate]

This question already has answers here:
How to submit a form with JavaScript by clicking a link?
(9 answers)
Closed 2 years ago.
i have a db records echoed out and formatted in a table with a delete link(icon) on each table row, indexed with a while loop as the data gets fetched from db.
On clicking the delete icon, i expect the particular indexed row to get deleted from db and also from the table .
Here are my codes:
<script>
function submitForm(){
document.getElementById("myform").submit()
}</script>
</head>
<body>
<table>
<tbody>
<?php
$rowIndex = 0;
while($row = mysqli_fetch_row($result){
$user = $row[0];
$address=$row[1];
$phone = $row[2];
echo '<tr>
<td>'.$user.'</td>
<td>'.$address.'</td>
<td>'.$phone.'</td>
<td>Delete(icon)
</tr>'
$rowIndex+=1;
}
?>
</tbody>
</table>
<form method ="post" id ="myform" action ="test.php" >
<input type="hidden" name="del">
</form>
on clicking the 'Delete' Link , i expect the javascript to submit the form and move to 'test.php'(though i intend to remain on same form, but that way i will know my form ACTUALLY got submitted). Please any help will be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>test javascript form test </title>
</head>
<body>
<form action="#" method="post">
<label>Username</label>
<input type="text" id="name"><br>
<label>Password</label>
<input type="password" id="password"><br>
<button onclick="data()" type="button">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script>
function data(){
var name = $("#name").val();
var pass = $("#password").val();
alert(name);
alert(pass);
}
</script>
</body>
</html>

PHP and Javascript issue. Function return always the last value

I searched this website and couldn't find an answer.
I have a php page that display a dropdown list with 2 choices. When on change, a Javascript execute a function that opens a php page to update my database, sending the ID and another parameter with the URL. The problem is the ID value is always the same (the last of the list). Can you help me please, I am very new in PHP and Javascript. Thank you in advance. Here is the PHP code and the javascript:
<?php
$AvailabilityCondition = "1=1";
if ((isset($_POST["availabilityChoice"])) && ($_POST["availabilityChoice"] !== "All")){
$AvailabilityCondition = "rented = "."'".$_POST["availabilityChoice"]."'";
}
$rentalquery = "SELECT * FROM rentals WHERE $AvailabilityCondition ORDER BY region_name, rental_name";
if ($rentalresult = $link->query($rentalquery)) {
/* fetch associative array */
while ($rowrentals = $rentalresult->fetch_assoc()) {
$NumberOfResults = $rentalresult->num_rows;
?>
<!-- ************************* This display a table with a short rental description (Region name - Rental name)
****************************** with and EDIT link, a DELETE link and an AVAILABILITY selector. ******************* -->
<div align="center">
<table >
<tr >
<td width="300" >
<?php echo ($rowrentals["region_name"]).' - '.($rowrentals["rental_name"]).'<br/>'; ?>
</td>
<td width="50">
EDIT
</td>
<td width="100" align="right">
<!-- *********** This form display the actual availability state. On change, it updates the database **************** -->
<form name="updateAvailability" method=POST" class="form-horizontal" >
<select onChange="showSelected(this.value)" id ="availabilityChoice" name="availabilityChoice" style="width: auto">
<option value="No" <?php if (($rowrentals["rented"]) == "No") echo 'selected="selected"' ?>>Available</option>
<option value="Yes" <?php if (($rowrentals["rented"]) == "Yes") echo 'selected="selected"' ?>>Rented</option>
</select> <?php echo ($rowrentals["id"]) ?>
</form>
<script type="text/javascript">
function showSelected(val){
document.getElementById ('availabilityChoice').innerHTML = val;
window.location.replace("status-update.php?rented=" + val + "&id=<?php echo ($rowrentals["id"]) ?>");
}
</script>
<!-- **************************************************************************************************************** -->
</td>
<td>
!!! DELETE !!!
</td>
</tr>
</table>
</div>
<?php
}}
/* free result set */
$rentalresult->free();
/* close connection */
$link->close();
?>
<br/><br/>
<div align="center">
<b>Back to Managers Main Menu</b>
</div>
</body> ​
I just posted more of my PHP page. So you can see the query and the WHILE, where $rowrentals["id"] is coming from.
Here is also a screen capture of how the page looks like: screen capture
I echoed the $rowrentals["id"] under each availability dropdown.
But whatever row I chose to change the availability, it always pass Id=9, the last one. That is what confuses me.
Before the screen capture, all five rows where "Available". Then I selected "Rented" on the first row. The page updated and since Id always =9, you can see the last row "Rented".
The Javascript is working to retrieve the value of the selected item. Because it opens this page perfectly: status-update.php?rented=Yes&Id=9
But again, Id is always 9...
Try with this:
<script type="text/javascript">
function showSelected(val){
document.getElementById ('availabilityChoice').innerHTML = val;
window.location.replace("status-update.php?rented=" + val + "&id=<?php echo ($rowrentals['id']) ?>");
}
If showSelected javascript function inside a foreach/while loop you need to extract it from loop and send id+value at the same time to showSelected function.
Thank you everybody. I found my answer. I added a counter, so this create a different function name for each database Id.
Here is the code:
$rentalquery = "SELECT * FROM rentals WHERE $AvailabilityCondition ORDER BY region_name, rental_name";
$counter =0;
if ($rentalresult = $link->query($rentalquery)) {
/* fetch associative array */
while ($rowrentals = $rentalresult->fetch_assoc()) {
$NumberOfResults = $rentalresult->num_rows;
$counter = $counter+1;
?>
<!-- ************************* This display a table with a short rental description (Region name - Rental name)
****************************** with and EDIT link, a DELETE link and an AVAILABILITY selector. ******************* -->
<div align="center">
<table >
<tr >
<td width="300" >
<?php echo ($rowrentals["region_name"]).' - '.($rowrentals["rental_name"]).'<br/>'; ?>
</td>
<td width="50">
EDIT
</td>
<td width="100" align="right">
<!-- *********** This form display the actual availability state. On change, it updates the database **************** -->
<form name="updateAvailability<?php echo $counter ?>" method=POST" class="form-horizontal" >
<select onChange="showSelected<?php echo $counter ;?>(this.value)" id ="availabilityChoice<?php echo $counter ?>" name="availabilityChoice<?php echo $counter ?>" style="width: auto">
<option value="No" <?php if (($rowrentals["rented"]) == "No") echo 'selected="selected"' ?>>Available</option>
<option value="Yes" <?php if (($rowrentals["rented"]) == "Yes") echo 'selected="selected"' ?>>Rented</option>
</select>
</form>
<script type="text/javascript">
function showSelected<?php echo $counter ;?>(val){
document.getElementById ('availabilityChoice<?php echo $counter ;?>').innerHTML = val;
window.location.replace("status-update.php?rented=" + val + "&id=<?php echo ($rowrentals["id"]) ?>");
}
</script> ​

How to update first td value onclickthe way it does when dragging

I have rewritten my question to better elaborate as to what I am trying to accomplish and what I have tried thus far.
I have a table on my website which dynamically loads the table rows from a database. I have successfully integrated the jQuery UI "Sortable" and "Draggable" functionality to this page. the outcome is the numeric value changes as you are dragging the rows above or below their neighboring rows and as a result always update the first column of numbers within the table.
Here is the table
<form action="" method="post" id="sort_picks">
<div class="sort-picks-container">
<table class="table-preference-order" id="sortable">
<tbody class="ui-sortable">
<?php
$counter = 1;
foreach ( $result as $query ){
$pickcheck = "SELECT * FROM picks";
$pickcutoffcheck = $wpdb->get_results( $wpdb->prepare ($pickcheck, OBJECT_K ));
foreach ($pickcutoffcheck as $pickcutoffresult) { ?>
<div style="display:none;"><?php echo $pickcutoffresult->pickCutoff; ?></div>
<?php } ?>
<?php $maxlimit = $wpdb->get_row("SELECT count(*) as CNT1 FROM picks where User='$userid'" ); ?>
<tr class="ui-state-default preference-row">
<td class="index preference-pick-order">
<input type="text" class="pick-order" id="sort" name="sort[]" pattern="[1-<?php echo $maxlimit->CNT1; ?>]{1,2}" value="<?php echo $counter; ?>" style="border:0px;max-width:60px;font-size:20px;" readonly>
</td>
<td class="preference-pick-order">
<input type="text" name="rem[]" class="borderless" style="text-align:left;width:25px;display:none;" value="<?php echo $query->REM; ?>" readonly><?php echo $query->REM; ?>
</td>
<td class="preference-emp-info">
<input type="text" name="empname[]" class="borderless" style="display:none;" value="<?php echo $query->EmpName; ?>" readonly><b><?php echo $query->EmpName; ?></b>
</td>
<td class="preference-start-class">
<input type="text" name="starttime[]" class="borderless" style="text-align:left;max-width:75px;display:none;" value="<?php echo $query->StartTime; ?>" readonly><?php echo $query->StartTime; ?>
</td>
<td class="preference-details">
<input type="text" name="job_details[]" class="borderless" value="<?php echo $query->Job_Details; ?>" readonly style="display:none;"><?php echo $query->Job_Details; ?>
<br>
<input type="text" name="startdate[]" class="borderless" style="font-weight:bold;width:100%;text-align:left;display:none;" value="<?php if($query->StartDate!=""){echo date('l\, F jS Y', strtotime($query->StartDate)); }?>" readonly><?php if($query->StartDate!=""){echo date('l\, F jS Y', strtotime($query->StartDate)); }?>
</td>
</tr>
<?php $counter++; ?>
<?php }?>
</tbody>
</table>
</div>
<br>
<div class="sorters-holder">
<button onclick="upNdown('up');return false;" class="sorters">&wedge; </button><br>
<button onclick="upNdown('down');return false;" class="sorters">&vee;</button>
</div>
<div style="display:block;margin:auto;text-align:center;">
<input type="submit" name="submit[]" value="Next" class="job-select-submit" id="validate"> <input type="button" onclick="window.history.go(-1); return false;" value="Back" class="job-select-submit">
</div>
</form>
This is the working jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js"></script>
<script src="../wp-content/themes/Excellence_At_Work/jquery.ui.touch-punch.min.js"></script>
<script>
var $j = jQuery.noConflict();
var sort;
$j(function() {
$j("#sortable tbody").sortable({
change: function(event, ui) {
sort = 0;
$j('#sortable tr.ui-state-default:not(".ui-sortable-helper")').each(function() {
sort++;
if ($j(this).hasClass('ui-sortable-placeholder'))
ui.helper.find('td input[name^=sort]').attr('name', 'sort[]').attr('value', sort).val(sort);
else
$j(this).find('td input[name^=sort]').attr('name', 'sort[]').attr('value', sort).val(sort);
});
}
});
$j("#sortable tbody").disableSelection();
});
</script>
<script>jQuery('#sortable').draggable();</script>
As you can see in the html code, I have successfully integrated the buttons that I need to relocate the rows however when doing so I need the value of the first td to also update accordingly as does the drab and drop method. What would I add to the below javascript to get the value of the input with the name sort[] to change to its corresponding numeric place within the table rows newly changed order onclick?
<script>
var order; // variable to set the selected row index
function getSelectedRow()
{
var table = document.getElementById("sortable");
for(var i = 0; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
if(typeof order !== "undefined"){
table.rows[order].classList.toggle("selected");
}
order = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction)
{
var rows = document.getElementById("sortable").rows,
parent = rows[order].parentNode;
if(direction === "up")
{
if(order > 0){
parent.insertBefore(rows[order],rows[order - 1]);
// when the row go up the index will be equal to index - 1
order--;
}
}
if(direction === "down")
{
if(order < rows.length){
parent.insertBefore(rows[order + 1],rows[order]);
// when the row go down the index will be equal to index + 1
order++;
}
}
}
</script>
I hope this better explains whatt I am trying to accomplish. I have hit a road block and could really use some insight, thanks in advance for all those who can provide insight.
UPDATE
I have been able to successfully update the rows first td values onclick by adding the following script after order-- and order++ however this solution is causing the input fields to drop out of the td. Any insight on how to modify this script to include the input field?
Array.prototype.forEach.call(document.querySelectorAll('td:first-child'), function (elem, idx) {
elem.innerHTML = idx + 1;
FINAL UPDATE
I have succeeded in my mission and with a minor adjustment to the snippet from the last update I was able to get the form above working as noted.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.
FINAL UPDATE
I have succeeded in my mission and with a minor adjustment to the snippet from the last update I was able to get the form above working as noted.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.

How to retain values of randomly generated HTML text fields on page refresh?

I am creating HTML text at runtime like my following code.
<?php
session_start();
for(var i=1;i<=10;i++)
{
?>
<div id="mainDiv<?php echo $i; ?>">
<input type="text" id="myText<?php echo $i; ?>">
<button type="button" id="myButton<?php echo $i; ?>" onclick="myButtonClicked()">Click Me</button>
</div>
<?php
}
?>
It is working fine. Problem is now in retaining the values of these textboxes. When I refresh the page, all the values previously entered are gone. Do I need to create 10 sessions to retain the values of these 10 texts? Or, is there any other way of doing this?
You can use the locaStorage api for retain the user input by store/get to/from localStorage after page refresh.
setItem() and getItem() are used for store and get item from localStorage respectively.
Example
This html will be created by php
<input type="text" id="text1" value="" />
<button type="button" id="myButton1" onclick="myButtonClicked('text1')">Click Me</button>
<input type="text" id="text2" value="" />
<button type="button" id="myButton1" onclick="myButtonClicked('text2')">Click Me</button>
//like this other input and button will be created.
JS
if(localStorage.getItem('resArr') == null){
var resultArr = [];
}else{
resultArr = JSON.parse(localStorage.getItem('resArr'));
//---- get stored item from localStorage by json parsing
}
alert('the last item you entered is ' + resultArr[resultArr.length-1]);
function myButtonClicked(id){
var userVal = document.getElementById(id).value;
resultArr.push(userVal);
localStorage.setItem('resArr', JSON.stringify(resultArr));
//stored the entered value in localStorage by doing stringify
}
DEMO
I don't know if this will help you exactly
but you can achieve what you want through a form that submits to php_self..
<?php
//create blank array for storing text box values
for($i=1;$i<=10;$i++){
$textValue[$i]='';}
//if page reached via submission of button, store posted text box values in array
if(isset($_POST['myButton'])){
for($i=1;$i<=count($textValue);$i++){
$textValue[$i]=$_POST['myText'.$i];}}
?>
<!--create form that submits to same page-->
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data" name="main">
<?php
//loop creates text boxes and buttons while getting text box default values from $textValue Array
for ($i=1;$i<=count($textValue);$i++){
echo '<div id="mainDiv'.$i.'">
<input type="text" id="myText'.$i.'" name="myText'.$i.'" value="'.$textValue[$i].'"/>
<button id="myButton'.$i.'" name="myButton" value="myButton'.$i.'">Click Me</button>
</div>
';}
?>
</form>

Categories