This is my first post here so I apologize in advance if the formatting is wrong.
I am working on a form that pulls data from MySQL using a loop and outputs it to HTML page. The user then has the option to approve or deny the entries, and based on user selection validation should be required or optional. My current code will validate correctly, but only for the first row being outputted from the loop. I am trying to validate all rows. I have tried using a while loop and foreach statement with no success. Any help would be greatly appreciated!
My Loop & Form:
//connect to the database
$db=mysqli_connect('localhost','root','') or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysqli_select_db($db,"my_db") or die(mysql_error());
//-query the database table
$sql="SELECT id, date, client_name, client_number, date_completed, status FROM clients WHERE client_name LIKE '%" . $search ."%' OR status LIKE '%" . $search ."%' ";
//-run the query against the mysql query function
$result=mysqli_query($db, $sql);
//-count results
$rows=mysqli_num_rows($result);
if($rows=mysqli_num_rows($result)) {
echo "<h2 style='margin-left: 10em;margin-bottom: -0.4em;'><br><br><br>" . $rows . " result(s) found for " . $search . "</h2><br />";
}elseif($rows=mysqli_num_rows($result) == 0) {
echo "<h2 style='margin-left: 10em;margin-bottom: -0.4em;'><br><br><br>0 result(s) found for " . $search . "</h2><br />";
}
//-create while loop and loop through result set
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
$date=$row['date'];
$client_name=$row['client_name'];
$client_number=$row['client_number'];
$date_completed=$row['date_completed'];
$status=$row['status'];
echo "<form method='post' enctype='multipart/form-data' action=''>";
echo "<table border='0'>";
echo "<tr>\n";
echo "<td>Timestamp</td><td>Client Name</td><td>Client Number</td>Status</td><td>Date Completed & Returned</td><td>Upload Zip Files</td>\n";
echo "</tr>";
echo "<tr>\n";
echo "<td readonly class='date'>$date</td>\n";
echo "<td><input readonly type='text' id='client_name' name='client_name' value='$client_name'></td>\n";
echo "<td><input readonly type='text' id='client_number' name='client_number' value='$client_number'></td>\n";
echo "<td><select id='status' name='status' aria-invalid='false'>
<option value=''>Select an option</option>
<option value='Denied'>Denied</option>
<option value='Approved'>Approved</option>
</select></td>\n";
echo "<td><input type='date' id='date_completed' name='date_completed_returned' value='$date_completed'></td>\n";
echo "<td><input type='file' id='upload' name='upload'></td>";
echo "<td class='submit'><input type='hidden' id='hidden' name='hidden' value='$client_name'><input type='submit' id='save' name='save' value='Save'></td>\n";
echo "</tr>";
echo "</table>";
echo "</form>";
}
My jQuery code:
I am trying to make date_completed and upload fields required if user selects "Approved" under status field, and optional if he selects "Denied".
<script>
$('#status').on('change', function() {
if ( this.value == 'Approved')
$("#date_completed").prop('required',true)
}).trigger("change"); // notice this line
$('#status').on('change', function() {
if ( this.value == 'Approved')
$("#upload").prop('required',true)
}).trigger("change"); // notice this line
</script>
Thanks to KevinB I was able to find a solution to my problem.
I added class names for the input fields (status, date_completed, upload) I was trying to validate:
Updated code below:
echo "<form method='post' enctype='multipart/form-data' action=''>";
echo "<table border='0'>";
echo "<tr>\n";
echo "<td>Timestamp</td><td>Client Name</td><td>Client Number</td>Status</td><td>Date Completed & Returned</td><td>Upload Zip Files</td>\n";
echo "</tr>";
echo "<tr>\n";
echo "<td readonly class='date'>$date</td>\n";
echo "<td><input readonly type='text' id='client_name' name='client_name' value='$client_name'></td>\n";
echo "<td><input readonly type='text' id='client_number' name='client_number' value='$client_number'></td>\n";
echo "<td><select id='status' name='status' class='status' aria-invalid='false'>
<option value=''>Select an option</option>
<option value='Denied'>Denied</option>
<option value='Approved'>Approved</option>
</select></td>\n";
echo "<td><input type='date' id='date_completed' name='date_completed' class='date_completed' value='$date_completed'></td>\n";
echo "<td><input type='file' id='upload' name='upload' class='upload'></td>";
echo "<td class='submit'><input type='hidden' id='hidden' name='hidden' value='$client_name'><input type='submit' id='save' name='save' value='Save'></td>\n";
echo "</tr>";
echo "</table>";
echo "</form>";
<script>
$('.status').on('change', function() {
if ( this.value == 'Approved')
$('.date_completed').prop('required',true)
}).trigger("change"); // notice this line
$('.status').on('change', function() {
if ( this.value == 'Approved')
$('.upload').prop('required',true)
}).trigger("change"); // notice this line
</script>
Related
I have a table of items and I would like to place an order button at the end of the table. The button would then take user to "order.php". Where based on the "Picture ID" they would then order the selected item. I've had a look at similar questions online however haven't been able to get it working with what I currently have.
if ($result->num_rows > 0)
{
echo "<table>\n";
while($row = $result->fetch_assoc())
{
echo "<tr>\n";
echo "<td>". $row["Picture ID"]."</td>\n";
echo "<td>". $row["name"]."</td>\n";
echo "<td>". $row["doc"]."</td>\n";
echo "<td>". $row["width"]."</td>\n";
echo "<td>". $row["height"]."</td>\n";
echo "<td>". $row["price"]."</td>\n";
echo "<td>". $row["description"]."</td>\n";
echo "<td> <form action='order.php' method='post'> <input type='button' name='id' value= ></form>"
echo "</tr>\n";
}
echo "</table>\n";
}
You have to pass the picture id as hidden input text and use the "submit" type for the button:
echo "<td> <form action='order.php' method='post'> <input type='hidden' name='id' value='" . $row["Picture ID"] . "'/> <input type='submit' name='submit' value='Buy'/></form>"
In order.php you can get the Picture ID from $_POST:
if (!empty($_POST['submit'])) { // submit button was pressed
echo 'Picture ID: ' . $_POST['id'];
}
Make sure to escape the $_POST['id'] properly when using it in SQL queries.
I've listed all the questions from my database randomly to a single page and I want to hide every other divs and show them 1 by 1.
I've tried using the LIMIT 1 on my query but the question will be shown repeatedly after processing it.
<?php
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM tbl_questions ORDER BY RAND();";
$result = mysqli_query($conn, $sql);
$questionCount = 1;
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$question = $row['question'];
$choice1 = $row['choice1'];
$choice2 = $row['choice2'];
$choice3 = $row['choice3'];
$choice4 = $row['choice4'];
$answer = $row['answer'];
echo "<div id='d$id'>";
echo "<h4>" . $questionCount++ . ". ". $question . "</h4>";
echo "<input type='radio' id='c1' name='c$id' value='1' checked />" . "
<label style='font-weight: normal' for='c1'>" . $choice1 . "</label><br/>";
echo "<input type='radio' id='c2' name='c$id' value='2' />" . "<label
style='font-weight: normal' for='c2'>" . $choice2 . "</label><br/>";
echo "<input type='radio' id='c3' name='c$id' value='3' />" . "<label
style='font-weight: normal' for='c3'>" . $choice3 . "</label><br/>";
echo "<input type='radio' id='c4' name='c$id' value='4' />" . "<label
style='font-weight: normal' for='c4'>" . $choice4 . "</label><br/>";
echo "<input type='submit' value='Submit' />";
echo "</div>";
}
You should put a new column in the database something column name like 'showhide' and by default put value 'show' and in the Query
$sql = "SELECT * FROM tbl_questions WHERE `showhide`='show' LIMIT 1";
On clicking submit button UPDATE value in database with value 'hide' so in the next load the submitted row will not come.
I'm trying to make a shopping page. I've kept checkboxes for selection and a number type field for quantity. As checkboxes are array I took the quantity field also an array... I know that we can check the checkbox state with checked method, now what I'm trying to achieve is to fetch corresponding quantity value and store it in a session varaible.
<?php
session_start();
if(isset($_POST['sub'])){
$_SESSION['cbb']=$_POST['cb'];
if(isset($_POST['qnty'])){
$_SESSION['qtty']=$_POST['qnty'];
header("location:userlogin.php");
}
}
?>
<html>
<head>
</head>
<body topmargin="20">
<font color='#7FFF00'>
<h1 align='center'>ONLINE SHOPPING</h1>
</font>
<form name="onshop" align="right" action="<?=$_SERVER["PHP_SELF"]?>"
method="post" onsubmit="return validate()">
<input type="submit" value="Add to cart" name="sub" style="background-
color:#7FFF00" />
<input type="reset" value="Reset" style="background-color:#7FFF00"/>
<?php
$db=mysqli_connect("localhost","root","","onlineshop");
if(!$db){
echo "Connection failure.";
}
$sql="SELECT * FROM stock";
$result=mysqli_query($db,$sql)or die("Invalid query ".mysqli_error($db));
echo "<TABLE width=50% height=70% align='center'>";
echo "<TR><TH>ITEM NAME</TH><TH>PRICE</TH><TH>IMAGE</TH><TH>Do you like?
</TH><TH>QUANTITY</TH></TR>";
while($myrow=mysqli_fetch_array($result))
{
echo "<TR><TD align='center'>";
echo $myrow["item"];
echo "</TD>";
echo "<TD align='center'>";
echo $myrow["price"];
echo "</TD>";
echo "<TD align='center'>";
$image=$myrow["image"];
echo '<img height="100" width="100" src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>';
echo "</TD>";
echo "<TD align='center'>";
$itm_id=$myrow["id"];
echo "<input type='checkbox' name='cb[]' value='$itm_id'>";
echo "</TD>";
echo "<TD align='center'>";
echo "<input type='number' name='qnty[]' value='1' max='50'
min='1'>";
echo "</TD>";
echo "</TR>";
}
echo "</TABLE>";
mysqli_close($db);
?>
</form>
<script type="text/JavaScript">
function validate(){
var count=0;
var i;
var cbelements = document.getElementsByName("cb[]");
if(count==0){
for(i=0;i<cbelements.length;i++){
if(cbelements[i].checked){
count++;
}
}
if(count<1){
alert("Select atleast 1 item.");
return false;
}
}
}
</script>
</body>
</html>
Can the onchange event be useful in anyway? or the associative array ?
I have a PHP form as below. Once user selects a particular row/rows I need to send the corresponding data to my PHP backend script. Here the externalID is unique. I face two issues in my code
Currently I get the entire form data to my PHP backend script,I need to data corresponding to only the rows I selected.
I have two buttons in the page and how can I call different php scripts on click of the button. Currently the click of "send MTDATA" calls the php script in form action.
src code:
<form target="iframe_b" action="/php_src/first.php" method="POST"
echo "sending data">
<fieldset>
<br><br>
<input type="button" id="activate_device" name="activatedevice" value="Activate_device">
<input type="submit" value="SEND MTDATA">
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>External ID</th>
<th>Status</th>
</tr>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'xxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ApplicationServer") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT EXTERNAL_ID,CONNECTION_STATUS FROM DEVICE_DETAILS") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$extID = $row['EXTERNAL_ID'];
$conStatus = $row['CONNECTION_STATUS'];
echo "</tr><tr>";
echo "</td><td>";
echo "<input type=\"checkbox\" class=\"case\" name=\"checkBox".$extID."\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classextID\" value=\"$extID\" name=\"textExID".$extID."\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classConnection\" value=\"$conStatus\" name=\"textcon".$extID."\" />";
}
?>
</table>
</fieldset>
</form>
output:
array(9) { ["checkBox123456#mydomain_com"]=> string(2) "on" ["textExID123456#mydomain_com"]=> string(19) "123456#mydomain.com" ["textcon123456#mydomain_com"]=> string(16) "request accepted" ["checkBox1234#mydomain_com"]=> string(2) "on" ["textExID1234#mydomain_com"]=> string(17) "1234#mydomain.com" ["textcon1234#mydomain_com"]=> string(16) "request accepted" ["checkBox53278#mydomain_com"]=> string(2) "on" ["textExID53278#mydomain_com"]=> string(18) "53278#mydomain.com" ["textcon53278#mydomain_com"]=> string(16) "request accepted" }
All html inputs - except unchecked checkboxes - are sent to the server so the only way to avoid that is to use javascript to remove the unselected rows from the form completely before the form is sent.
However, if the total amount of data is not the problem but you just want to be able to easily select the checked rows, you should use arrays in your html:
echo "<input type=\"checkbox\" class=\"case\" name=\"checkBox[".$extID."]\" />";
^ array ^
echo "</td><td>";
echo "<input type=\"text\" class=\"classextID\" value=\"$extID\" name=\"textExID[".$extID."]\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classConnection\" value=\"$conStatus\" name=\"textcon[".$extID.]"\" />";
Now your $_POST['checkBox'], etc. variables will be arrays in php as well so you can easily loop over them as the key is your $extID value. And as I mentioned before, only the checked checkboxes are sent to the server:
// Loop over the sent-in / selected checkboxes
foreach (array_keys($_POST['checkBox']) as $key) {
var_dump($_POST['textExID'][$key]);
// etc.
}
Also note that your html is probably not valid as you are not closing the last row but I don't think that would be causing any problems with the form.
One way is to collect the input in an array.
<?php
echo "</tr><tr>";
echo "</td><td>";
echo "<input type='checkbox' class='case' name='$extID[ checkBox ]' />";
echo "</td><td>";
echo "<input type='text' class='classextID' value='$extID' name='$extID[ textExID ]' />";
echo "</td><td>";
echo "<input type='text' class='classConnection' value='$conStatus' name='$extID[ textcon ]' />";
?>
Then if you check the $_POST you will find an array within an array, loop the first array and collect the details for each $extID.
As for the two buttons, you could name the submit button and then check to see which has been pressed.
<input type="button" id="activate_device" name="activatedevice" value="Activate_device">
<input type="submit" value="SEND MTDATA" name="submit_button">
<?php
if( isset( $_POST[ 'submit_button' ] ) )
{
// Process submit
}
elseif( isset( $_POST[ 'activatedevice' ] ) )
{
// Process device
}
Hello guys I just want to ask how can i create a jquery that can detect the user input and assign an attribute or remove an attribute based on the user input.
My scenario is I have a table with 4 columns. First is a dropdown. And the rest are textboxes which are readonly.
The default option for dropdown is NULL or empty. If the user choose from the dropdown, the 2 texboxes should not be readonly. On that process I don't have an error but if the user set back again to NULL. The 2 textboxes won't go back to readonly again. I don't know where's my error.
Here's my jquery code:
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate != ''){
$("#qty"+index).removeAttr('readonly');
$("#price"+index).removeAttr('readonly');
}
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate == ''){
$("#qty"+index).attr('readonly');
$("#price"+index).attr('readonly');
}
});
And this is my table
for($i = 1; $i < 16; $i++){
echo "<!-- ITEM {$i} -->";
echo "<tr>";
echo "<td>";
echo "<select name='code[]' id='code{$i}' style='width:100'>";
echo "<option value=''><label>--CHOOSE ITEMS--</label></option>";
foreach($resultGetCode->result_array() as $list){
echo "<option value='".$list['itemid']."'>".$list['itemcode']." --- ".$list['itemname']."</option>";
}
echo "</select>";
echo "</td>";
//echo "<td><input type='text' name='item[]' class='k-textbox' id='item{$i}' value='' /></td>";
echo "<td><input type='text' name='qty[]' id='qty{$i}' style='text-align: center' readonly='readonly' /></td>";
echo "<td><input type='text' name='price[]' id='price{$i}' style='text-align: right;' onblur='' readonly='readonly' /></td>";
echo "<td><input type='text' name='total[]' id='total{$i}' style='font-family: courier; text-align: right; background-color: lightgray; color: red' readonly='readonly' value='' /></td>";
echo "<tr>";
}
Here's the fiddle: http://jsfiddle.net/rochellecanale/jnkc3/5/
Would be easier to help you if you create a fiddle, but try this
if(validate == ''){
$("#qty"+index).prop('readonly', true);
$("#price"+index).prop('readonly', true);
}
Update. FIDDLE