PHP array checkbox issue, keep the 'right' boxes checked after submit - javascript

I am currently created a checkbox system based on each school in an array. Everything works fine except, that after submit, only the first checkboxes are checked.
Example: I have 10 checkboxes, and check box number 4,5 and 6. After submit, box 1,2 and 3 are checked.
I want box 4,5 and 6 to keep their selection after submit.
Hope that you can imagine by problem.
<!--Start Checkbox system for schools-->
<form method="POST">
<?php
$q = "SELECT id, name FROM $school_table";
$result = mysqli_query($con, $q);
while(($row = mysqli_fetch_array($result))) {
//First line of <input>
echo '<input type="checkbox" name="check_list[]" value="';
//Value of the input (school ID)
echo $row['id'] .'"';
//Keep the box checked after submit. PROBLEM MIGHT BE HERE!!!
if(isset($_POST['check_list'][$row['id']])){echo 'checked="checked"';}
//Echos the school name out after the checkbox.
echo '>' . $row['name'] . " <br> ";
}
?>
<script language="javascript">
//Select all on/off function
function checkAll(bx) {
var cbs = document.getElementsByTagName('input');
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
</script>
<!--Check all mark. Works with Javascript written above-->
<input type="checkbox" name="check_all" onclick="checkAll(this)" <?php if(isset($_POST['check_all'])){echo "checked";} ?>> Check all: On/Off
<input type="submit" name="submit" value="sort">
</form>
<!--End Checkbox system for schools-->
Image of the problem. Take a look
Hope you guys can help me out :)

I didn't have your MySQL, so I simulated it with by creating some rows using a for loop.
<html>
<!--Start Checkbox system for schools-->
<head>
<title>Test checklist</title>
</head>
<body>
<form method="POST">
<?php
for ($i = 0; $i < 10; $i++) {
$rows[$i]['id'] = $i*2+1;
$rows[$i]['name'] = "Name ".strval($i*2+1);
}
// $q = "SELECT id, name FROM $school_table";
//$result = mysqli_query($con, $q);
//while(($row = mysqli_fetch_array($result))) {
foreach ( $rows as $row )
{
//First line of <input>
echo '<input type="checkbox" name="check_list['.$row['id'].']" value="checked"';
//Keep the box checked after submit. PROBLEM MIGHT BE HERE!!!
if(isset($_POST['check_list'][strval($row['id'])])){
echo 'checked="checked"';}
//Echos the school name out after the checkbox.
echo '>' . $row['name'] . " <br>\n";
}
?>
<script language="javascript">
//Select all on/off function
function checkAll(bx)
{
var cbs = document.getElementsByTagName('input');
for(var i=0; i < cbs.length; i++) {
if(cbs[i].type == 'checkbox') {
cbs[i].checked = bx.checked;
}
}
}
</script>
<!--Check all mark. Works with Javascript written above-->
<input type="checkbox" name="check_all" onclick="checkAll(this)" <?php if(isset($_POST['check_all'])){
echo "checked";} ?>> Check all: On/Off
<input type="submit" name="submit" value="sort">
</form>
<!--End Checkbox system for schools-->
</body>
</html>
The key line is this one:
echo '<input type="checkbox" name="check_list['.$row['id'].']" value="checked"';
You need to set the array index in check_list to your row id. Otherwise the
rows in the array are going to be 0 based and have values = your row id. Your value for the post field really isn't used the way you are coding it.
check_list[0] = '1'
check_list[1] = '3'
check_list[2] = '5'

Related

Select dropdown option and display table (javascript)

With a SELECT query I obtain an array of 7 names, create a dropdown list and each name is a table which is then hidden.
I want to click on the name in the dropdown list and display the table.
I am not receiving any errors but the following code only displays the first table in the array no matter what option is selected. I have little knowledge of javascript and the function has been cobbled together from various queries on the site.
Javascript:
function changeOpt(clicked) {
var x = document.getElementById("optChange");
var optVal = x.options[x.selectedIndex].value;
for(var i =0; i<x.length;i++){
if(optVal = document.getElementById('datath'))
document.getElementById('data').style.display = 'block';
}
}
HTML/PHP:
while($row = mysqli_fetch_array($result))
{
$array = $row;
//echo '<pre>'.print_r($array).'</pre>';
echo '<table id="data" style="display:none;">';
echo '<tr><td>You searched for:</td></tr>';
echo '<tr><th id="datath">'.$row[0].'</th><th>'.$row[1].'</th><th>'.$row[2].'</th>';
echo '</tr>';
echo '</table>';
$option .= '<option value = "'.$row['1'].'">'.$row['1'].'</option>';
}
?>
<form method="post" action="#" id="my_form" >
<select id="optChange" name="opt" onchange="changeOpt(this.id)">
<option><--select a name--></option>
<option><?php echo $option; ?></option>
</select>
<input type="button" name="submit" value="submit" >
</form>
Am I completely off-beam ? Can someone give me some guidance please to get my code straight.

how to clear multple select box data

I want to clear the selected data on multiple select boxes but it won't work for me.
<select name="age" id="age" class="span2 typeahead" multiple data-rel="chosen">
<?php
$age_arr = explode(",", $result['age']);
foreach ($age as $a)
{
$select = "";
for ($is = 0; $is < count($age_arr); $is++)
{
if ($age_arr[$is] == $a['age_id'])
{
$select = "selected";
}
} ?>
<option id="age2" value="<?php echo $a['age_id']; ?>" <?php echo $select; ?>><?php echo $a['age']; ?></option>
<?php
}
?>
</select>
<input type="hidden" id="age_val" name="age_val" value="<?php echo $result['age']; ?>" />
<input type="button" value="Clear" id="clear" class="btn" onClick="clearFields()">
This is what I tried:
<Script>
function clearFields(){
document.getElementById("age_val").value = "";
document.getElementById("age").value = '';
}
</Script>
Please advice me how to clear data when clear button clicked,
selectbox
As you have a multiple select, not a standard select, you need to set the selected property of each option element to false. Try this:
function clearFields() {
$('#age option:selected').prop("selected", false);
$('#age_val').val('');
}
Working example
Javascript:
function clearFields(){
document.getElementById("age_val").value = "";
var collection = document.getElementById('age').getElementsByTagName('option');
for(var i = 0; i<collection.length; i++){
collection[i].selected = false;
}
// for chosen
$('#age').trigger('chosen:updated');
}
But as long as you using jquery, then you can use code in answer provided by #Rory McCrossan and add to the function: $('#age').trigger('chosen:updated');

Disable text-boxes generated dynamically on multiple rows, based on user's selection

The system asks the user to identify the number of records they would like to enter, based on their selection (say 3), the system displays three text boxes.
<?php for($i=1; $i<=$rows; $i++) { ?> // $i is 3 here
<input type="text" name="company_name[]" id="cn[]">
<input type="text" size="3"name="entertainment[]" id="en[]">
<?php } ?>
So this will generate 3 rows, with the same text boxes. If the user enters a value in the 1st row for entertainment, the company name should get grayed out or vice versa. Similarly it should do the same for the 2nd and 3rd line as well - based on which text box they fill.
How do I do that via js/jquery?
P.S: I am not a good front-end developer, so I could use all the help I can get.
Thanks.
First wrap then into <div>.
Element Id should be unique, change it as following
<?php for($i=1; $i<=$rows; $i++) { ?> // $i is 3 here
<div>
<input type="text" name="company_name[]" onchange="grayOther(this);" id="cn_<?php echo $i ?>">
<input type="text" size="3"name="entertainment[]" onchange="grayOther(this);" id="en_<?php echo $i ?>">
</div>
<?php } ?>
Then here is the js.
<script>
function grayOther(elem){
elem = $(elem); // convert to jquery object
if (elem.val().length == 0) {
elem.siblings().prop('disabled',false);
}else {
if (elem.is("[name='company_name[]']")){
elem.siblings("[name='entertainment[]']").prop('disabled',true);
}else {
elem.siblings("[name='company_name[]']").prop('disabled',true);
}
}
}
</script>

checked checkbox will remain through pagination

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

SQL Generated select menu, updating textbox based on related value

Some Background information:
I have a table with two fields, TECHNAME and TECHCOLOR
What I am trying to do is:
Have a SQL generated Drop down menu based on TECHNAME (DONE)
Have TECHCOLOR update in text box when TECHNAME is selected (ISSUE IS HERE)
What is wrong
Currently, the textbox is showing TECHNAME insead of TECHCOLOR
Code
JavaScript:
<script type="text/javascript">
function load_value(value)
{
document.getElementById("test").value=value;
}
</script>
HTML/PHP:
<table>
<form method="post" action="">
<?php
$select_box='<select name="edittech" id="edittech" onchange="javascript:load_value(this.value);">';
$input="";
$result = $conn->query("select * from techs");
while ($row = $result->fetch_assoc()) {
$select_box .='<option id="name" value="'.$row["TECHNAME"].'">'.$row['TECHNAME'].'</option>';
}
$input ='<input type="text" name="test" id="test" value="" />';
echo $select_box."</select>";
echo $input;
?>
Thanks in advance! :D
When you submit the form, is the value for your edittech dropdown list used at all? If it isn't then you can simply change the value part of your dropdown to be TECHCOLOR and it will still show TECHNAME on the dropdown.
while ($row = $result->fetch_assoc()) {
$select_box .= "<option id=\"name\" value=\"{$row['TECHCOLOR']}\">{$row['TECHNAME']}</option>";
}

Categories

Resources