Changing input field based on other input field? - javascript

I want to have the datalist from "Serienummer" change based on what "Product" is chosen.
<td>Product</td>
<td>
<Select name="ProductID" placeholder="Productnaam" required>
<?php
$query2 = "SELECT DISTINCT ProductID FROM HW_Serial WHERE Prefix = '$prefix'";
$result2 = mssql_query($query2);
$numRows = mssql_num_rows($result2);
while($row = mssql_fetch_array($result2))
{
$DisProductID=$row["ProductID"];
$query3 = "SELECT ProductID, ProductName FROM Products WHERE ProductID = '$DisProductID' order by ProductName";
$result3 = mssql_query($query3);
$numRows = mssql_num_rows($result3);
while($row = mssql_fetch_array($result3))
{
$xProductID=$row["ProductID"];
$xProductName=$row["ProductName"];
if ($ProductID == $xProductID) {
echo "<OPTION value =\"$xProductID\">$xProductName</OPTION>";
} else {
echo "<OPTION value =\"$xProductID\">$xProductName</OPTION>";
}
}
}
?>
</select>
</tr>
<tr>
<td>Serienummer</td>
<td>
<input list="devicesn" name="devicesn" autocomplete="off" placeholder="Serienummer" required>
<datalist id="devicesn">
<?php
$query2 = "SELECT devicesn FROM HW_Serial WHERE ProductID = '$ProductID' order by devicesn";
$result2 = mssql_query($query2);
$numRows = mssql_num_rows($result2);
while($row = mssql_fetch_array($result2))
{
$xdevicesn=$row["devicesn"];
if ($devicesn == $xdevicesn) {
echo "<OPTION value =\"$xdevicesn\">$xdevicesn</OPTION>";
} else {
echo "<OPTION value =\"$xdevicesn\">$xdevicesn</OPTION>";
}
}
?>
My guess is that this has to be done by use of JavaScript but I'm a complete beginner when it comes to that.
Thanks in advance

You can redirect to current page with parameter when <select> changed. And receive the parameter in your php code in datalist section.
For example:
<select name="ProductID" placeholder="Productnaam" required onchange="location.href='?product' + this.value">...</select>
Then I just say sorry, I do not know how to receive url parameters like yourpage?p=project in PHP.

Related

How to use ajax requests in table pagination and customization

I have a table that displays the records stored in a database. I have customized my pagination differently from what bootstrap uses to look like phpMyAdmin table pagination. What I have done so far works perfectly but refreshes the page on each user selection. I am stuck on how to use ajax to make the pagination work fine without refreshing the page.
Here's the HTML code to display the table with checkbox, select input and pagination links
<!--DISPLAY TABLE-->
<form class="" name="frmDisplay" id="frmDisplay" method="POST" action="">
<div id="display_table"></div>
<input type="checkbox" name="check" id="check" onchange=""></input> <label for="check">Show All</label>
<label class="clabel">|</label>
<label class="clabel" for="rowno">Number of Rows:</label>
<select class="" id="rowno" name="rowno" style="width:50px;height:25px;margin-bottom:3px;">
<option value='all' hidden disabled>All</option>
<?php
//set the value of $rowno
$rowno = isset($_POST['rowno'])?$_POST['rowno']:5;
if($rowno == 5)
{
$rowno = isset($_GET['limit'])?$_GET['limit']:5;
}
?>
<option value='5' <?=$rowno==5?'selected':''?>>5</option>
<option value='10' <?=$rowno==10?'selected':''?>>10</option>
<option value='15' <?=$rowno==15?'selected':''?>>15</option>
<option value='20' <?=$rowno==20?'selected':''?>>20</option>
<option value='25' <?=$rowno==25?'selected':''?>>25</option>
<option value='30' <?=$rowno==30?'selected':''?>>30</option>
</select>
<label class="clabel">|</label>
<label class="clabel" for="filter">Filter Rows:</label>
<input class="" style="width:50%;height:25px;margin-bottom:10px;" id="filter" name="filter" placeholder="Filter this table" onkeyup="filtertbl();"></input>
<div class='table-responsive-sm' style='width:100%;margin-top:10px;'>
<?php
//code to fetch all records from database on checkbox checked
if(isset($_POST['check']))
{
$sql = "SELECT *FROM evatbl WHERE RegNo = ?";
if($stmt = $con->prepare($sql))
{
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows>0)
{
$count = 1;
echo "<table id='t01'' class='table'>
<tr id='tblhead'>
<th>SN</th>
<th>Course Title</th>
<th>Course Code</th>
<th>Credit Unit</th>
<th>Course Lecturer</th>
<th>Rating(%)</th>
</tr>";
while($row = $result->fetch_assoc())
{
$ccode = $row['CourseCode'];
$ctitle = $row['CourseTitle'];
$cunit = $row['CreditUnit'];
$clec = $row['CourseLecturer'];
$crate = $row['Rating'];
echo "
<tr>
<td>$count</td>
<td>$ctitle</td>
<td>$ccode</td>
<td>$cunit</td>
<td>$clec</td>
<td>$crate</td>
</tr>";
$count++;
}
}
else{
echo "<p style='color:darkblue;margin-bottom:0;'>Oops! No records found.</p>";
}
}
}
else
{
//code for pagination
//get current page
$currentpage = isset($_GET['currentpage']) ? $_GET['currentpage'] : 1;
$no_of_records_per_page = $rowno;
$setoff = ($currentpage - 1) * $no_of_records_per_page;
//get total number of records in database
$sqlcount = "SELECT *FROM evatbl WHERE RegNo = ?";
$stmt = $con->prepare($sqlcount);
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
$totalpages = ceil($num_rows/$no_of_records_per_page);
//query for pagination
$sqllimit = "SELECT *FROM evatbl WHERE RegNo = ? ORDER BY CourseTitle LIMIT $setoff, $no_of_records_per_page";
if ($stmt = $con->prepare($sqllimit))
{
$stmt = $con->prepare($sqllimit);
$stmt->bind_param("s", $pregno);
$pregno = $_SESSION['regno'];
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if ($num_rows>0)
{
$count = 1;
echo "<table id='t01' class='table' width='100%'>
<tr id='tblhead'>
<th>SN</th>
<th>Course Title</th>
<th>Course Code</th>
<th>Credit Unit</th>
<th>Course Lecturer</th>
<th>Rating(%)</th>
</tr>";
while($row = $result->fetch_assoc())
{
$ccode = $row['CourseCode'];
$ctitle = $row['CourseTitle'];
$cunit = $row['CreditUnit'];
$clec = $row['CourseLecturer'];
$crate = $row['Rating'];
echo "
<tr>
<td>$count</td>
<td>$ctitle</td>
<td>$ccode</td>
<td>$cunit</td>
<td>$clec</td>
<td>$crate</td>
</tr>";
$count++;
}
}
else{
echo "<p style='color:darkblue;margin-bottom:0;'>Oops! No records found.</p>";
}
echo "</table>";
?><br>
<div class="nav_div">
<?php
//First Page Button
if($currentpage > 1)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."&currentpage=".(1)."' title='First'><<</a>";
}
//Previous Page Button
if($currentpage >= 2)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."&currentpage=".($currentpage - 1)."' title='Previous'><</a>";
}
?>
<select class='navno' name='navno' id='navno' onchange="pageNav(this)">
<?php
//Link to available number of pages with select drop-down
for($i = 1; $i <= $totalpages; $i++)
{
echo "<option class='bold'";
if ($currentpage==$i)
{
echo "selected";
}
echo " value='view_eva.php?limit=".$rowno."&currentpage=".$i."'>".$i."</option>";
}
?>
</select>
<?php
//Next Page Button
if($currentpage < $totalpages)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."&currentpage=".($currentpage + 1)."' title='Next'>></a>";
}
//Last Page Button
if($currentpage <= $totalpages - 1)
{
echo "<a class='nav_a' href='view_eva.php?limit=".$rowno."&currentpage=".($currentpage = $totalpages)."' title='Last'>>></a>";
}
?>
</div>
<?php
}
}
?>
</form>
</div>
</div>
Here's the javascript that controls form submission on each user selection. I know this is where I'll need to use ajax requests but I can't figure out how. I've been on this for some days now.
<script type="text/javascript">
<?php
/*Using PHP to create a javascript variable that can be used to
add the `selected` attribute to the respective option*/
printf("let rownum='%s'", empty($_POST['rowno']) ? 0 : $_POST['rowno']);
?>
let myForm=document.forms.frmDisplay;
let mySelect=myForm.rowno;
let myCheck=myForm.check;
let myNavSelect=myForm.nav_no;
// find all options and if the POSTed value matches - add the selected attribute
// establish initial display conditions following page load / form submission
if(rownum)
{
if(rownum=='all') myCheck.checked=true;
Array.from(mySelect.querySelectorAll('option')).some(option=>
{
if(rownum==Number(option.value) || rownum=='all')
{
option.selected=true;
return true;
}
});
}
// listen for changes on the checkbox
myCheck.addEventListener('click',function(e)
{
if(myCheck.checked)
{
var msg = confirm('Do you really want to see all of the \nrows? For a big table this could crash \nthe browser.');
if(!msg)
{
myCheck.checked=false;
return false;
}
}
if(mySelect.firstElementChild.value=='all')
{
mySelect.firstElementChild.selected=this.checked;
mySelect.firstElementChild.disabled=!this.checked;
}
myForm.submit();
});
// listen for changes on the select
mySelect.addEventListener('change',function(e)
{
if(myCheck.checked) myCheck.checked=false;
myForm.submit();
});
//load url on the navigate select
function pageNav(option)
{
location.href = option.value;
}
</script>
Please, I need all the help I can get to complete this project. Thank you.

PHP Driven Select Functions

I have a drop down that is enabled by default and shows options populated from the database. When an option is selected that is now blank it enables the drop down to the side if it.
echo '
<script>
function check(){
if(document.getElementById("company").value!="")
document.getElementById("stores").disabled=false;
else
document.getElementById("stores").disabled=true;
}
</script>
<label class="form-control-label" for="input-last-name">Company</label>
<select type="text" id="company" name="company" class="form-control form-control-alternative" onchange="check()">
<option></option>';
$sql = "SELECT * FROM companies WHERE CompanyID != '4'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['CompanyID'].'>'.$row['CompanyName'].'</option>';
}
}
echo'
</select>
<label class="form-control-label" for="input-last-name">Store </label>
<select id="stores" name="stores" class="form-control form-control-alternative" disabled>
<option></option>';
$sql = "SELECT * FROM stores";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['storeid'].'>'.$row['storename'].'</option>';
}
}
echo '
</select>';
As you can see selecting an item from the companies dropdown enables the stores dropdown to be enabled. However at the moment it shows all stores - not stores assigned to that company the SQL needs to be
SELECT * FROM store WHERE StoreID = $SelectedCompanyID
and not
SELECT * FROM store
I cannot work out a way to populate a variable to complete the query and reload the drop down correctly with correct stores without reloading the page and loosing the rest of the inputs already completed in the form.
Any help would be appreciated.
Created a new page called fetch_data.php with the following code below
<?php
if(isset($_POST['get_option']))
{
include('includes/config.php');
$companies = $_POST['get_option'];
$sql = "SELECT * FROM stores WHERE companyid = '$companies'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['storeid'].'>'.$row['storename'].'</option>';
}
}
exit;
}
?>
Changed my HTML / PHP to look like this
echo '
<script>
function check(){
if(document.getElementById("company").value!="")
document.getElementById("stores").disabled=false;
else
document.getElementById("stores").disabled=true;
}
</script>
<label class="form-control-label" for="input-last-name">Company</label>
<select type="text" id="company" name="company" class="form-control form-control-alternative" onchange="check()">
<option></option>';
$sql = "SELECT * FROM companies WHERE CompanyID != '4'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value='.$row['CompanyID'].'>'.$row['CompanyName'].'</option>';
}
}
echo'
</select>
<label class="form-control-label" for="input-last-name">Store </label>
<select id="stores" name="stores" class="form-control form-control-alternative">
</select>';
Then finally implemented in the JavaScript to do it.
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: "post",
url: "fetch_data.php",
data: {
get_option:val
},
success: function (response) {
document.getElementById("stores").innerHTML=response;
}
});
}
</script>

How to Select one of the same name values in one column via input type and then submit button?

What Im trying to do is put one name into a input type box and press submit, once submitted Id like it only to show all the same name rows and NOT all names in database? Can anyone help as I'm trying out or || in the PHP but only getting all results?
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<button onclick="refreshMap()">Refresh</button>
</form>
function refreshMap() {
var name = $('#name').val();
}
<script>
$(function() {
$('#name').val(name);
});
</script>
PHP:
$query = "SELECT * FROM register WHERE name IN ('John' || 'Gina')";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
}
if(!empty($_POST['name']))
{
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}
EDIT:
$name = htmlspecialchars($_POST['name']);
if(!empty($name))
{
$query = "SELECT * FROM register WHERE name LIKE '" .$name ."'";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
exit(0);
}
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}

Onchange form filter with dropdown

I am trying to create a filter for a gallery that I've created. The gallery has 5 filters using dropdown menu's. When a item is selected from one of the 5 filters it has to filter the images. When a second filter is selected it has to filter the results of the first filter and so on.
I am using the onchange='this.form.submit()' script but I don't know how to assign a certain action to it when an item is selected. This is my code at the moment of writing:
<td>
Kleur:
<form method="POST">
<select name="kleur" onchange='this.form.submit()'>
<option> -- Geen optie -- </option>
<?php while ($line1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $line1['kleur']; ?>"> <?php echo $line1['kleur']; ?>
</option>
<?php } ?>
</select>
</form>
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
</br>
</td>
The following part doesn't seem to work:
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
Does anyone know how to use this script? and perhaps explain how to save the selected item in the dropdown menu too?
You can add an attribute with all the information you need to filter to your images
<img filterInfo="Kleur|Geur|Bloemvorm|Gezondheid|Type|Zoeken">
then set a class for all your filters to catch the changes
$(".filters").on("change",function(){
var kleur = $('[name=Kleur]').val();
var Geur = $('[name=Geur]').val();
...
...
...
$.each($('#gallery img'),function(i,v){
var attrs = $(v).attr("filterInfo").slice("|");
if((kleur == "" || kleur == attrs[0]) && (Geur == "" || == attrs[1]) .... other filters)
$(this).show(); //or fadeIn();
else
$(this).hide(); //or fadeOut();
});
});

checking dynamically created textboxes for values

I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };

Categories

Resources