How to populate check boxes from Mysql database? - php

I want to retrieve data to check-box list when user selected an option from a drop-down list. So, the main categories are loaded in a drop-down list and subcategories are suppose to be loaded in a list of check-boxes. Right now, I sorted out to populate data to another drop-down list. here is my code:
JQuery Code:
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader" style="position:inline;"><img src="device manager/img/loading.gif" alt="loading subcategory" /></div>');
$.get('user manager/loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
PHP Code:
<tr>
<?php
include('config.php');
$query_parent = mysql_query("SELECT * FROM tblclient") or die("Query failed: ".mysql_error());
?>
<form method="get">
<tr>
<td><label>Client</label></td>
<td>
<select name="parent_cat" id="parent_cat">
<option selected="selected" disabled="disabled">Select a Client</option>
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['clientId']; ?>"><?php echo $row['clientName']; ?></option>
<?php endwhile; ?>
</select>
</td>
</tr>
<br/><br/>
<tr>
<td><label>Branch</label></td>
<td>
<select name="sub_cat" id="sub_cat" multiple>
<option selected="selected" disabled="disabled">Select a Branch</option>
</select>
</td>
</tr>
</form>
Loading subcategory list PHP Code:
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$query = mysql_query("SELECT B.*, C.* FROM tblbranch B INNER JOIN tblclientbranch CB on CB.branchId = B.branchId INNER JOIN tblclient C ON CB.clientId = C.clientId WHERE C.clientId = {$parent_cat}");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[branchId]'>$row[branchName]</option>";
}
?>
Does anyone know how to populate subcategories to a list of check-boxes?
Any solution would be great.
Thanks for reading my long code!

something like
<input type="checkbox" name="branch" value="$row[branchid]">$row[branchname]<br>

Related

Add table row , table data contain drop down which populate from database

Add new table row with category, item, measurement, price. I was able to add a new row but was unsure how to populate drop-down data from the database. I have to fetch data for the first row. This is my code.
<tbody>
<tr>
<td><input type="checkbox" name="record"></td>
<td>
<select id="catid" name="catid[]">
<option value="">Select Category</option>
<?php
$getcatid = "SELECT catid,catname FROM category";
$result = mysqli_query($conn,$getcatid);
while($row = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $row['catid']; ?>"><?php echo $row['catname']; ?></option>
<?php }?>
</td>
<td>
<select id="itemid" name="itemid[]">
<option value=''>Select Item</option>
</select>
</select>
</td>
<td>
<select id="msr" name="msr[]" onchange="showPrice(document.cument.getElementById('itemid').value,this.value)">
<option value=''>Measurement</option>
</select>
</td>
<td><div id="price"><input type="text" name="price[]"></div></td>
<td><input type="text" name="qty[]"></td>
<td><input type="text" name="total[]"></td>
</tr>
</tbody>
This is my script for add & remove row
$(document).ready(function(){
$("#add-row").click(function(){
var markup = "<tr><td><input type='checkbox' name='record'></td><td><select name='proid' id='proid'></select></td><td><select></select></td><td><select></select></td><td><input type='text name=''></td><td><input type='text' name=''></td><td><input type='text name=''></td></tr>";
$("table tbody").append(markup);
});
// Find and remove selected table rows
$("#delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
Try this code.
You need to use clone() in jquery.
Here is the jquery script and added working fiddle link.
Fiddle Link
$(document).on("click","#add-row", function(){
var markup = $("table tbody>tr:last").clone();
$("table tbody").append(markup);
});
// Find and remove selected table rows
$(document).on("click","#delete-row", function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});

Dynamic dropdown with auto select one option and it's sub-dropdown options

I have a dropdown in which one is for states and second one is it's sub category, which shows name of cities on basis of first dropdown.
Right now user need to select one category then subcategories load,
What change I want is "To set one value as default and load it's subcategories too" at load of page, and further user select different category so it should load it's subcategories accordingly.
Index.php:
<form name="insert" action="" method="post">
<table width="100%" height="117" border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%">
<select onChange="getdistrict(this.value);" name="state" id="state" class="form-control">
<option value="">Select</option>
<?php $query =
mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>">
<?php echo $row['StateName'];?>
</option>
<?php }?>
</select>
</td>
</tr><tr>
<th scope="row">District :</th>
<td>
<select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data: "state_id=" + val,
success: function (data) {
$("#district-list").html(data);
},
});
}
</script>
get_district.php:
<?php
require_once("config.php");
if(!empty($_POST["state_id"])){
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query)){
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>
You would need to do 2 things
1.) insert a selected flag into the input
2.) activate the second dropdown on page load
1.) If the selected entry does never change then hardcode the default selected field in your code like if $var = XXX then echo "selected".
If you have any function which calculates the default value e.g. a geolocation service like e.g. maxmind.com which takes the users remote IP address and outputs his current state, then use this result to set the selected entry.
<?php
while($row=mysqli_fetch_array($query)){
$row["StCode"] == "DESIRED_VALUE" ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> ><?php echo $row['StateName'];?>
</option>
[...]
Or add a field in the table SELECTED where you mark the default record with 1.
<?php
while($row=mysqli_fetch_array($query)){
$row["selected"] == 1 ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> >
<?php echo $row['StateName'];?>
</option>
[...]
2.) You have to set the second select dropdown on page load. There are several ways to do this - this is explained here in detail:
Jquery execute onchange event on onload

How do I selectively add 3rd select box or relabel & redirect to a 2nd select box?

I have a form where the 1st select box is required. Depending on the selection, a different table will be used as a source for the query to populate a 2nd select box. Then depending also on the 1st selection a 3rd select box may or may not be necessary. I have designed the form to initially show 3 select boxes, but the user would have to know to skip the 2nd select box in some cases. This is confusing at the least. As an example:
If None is selected for Company, then both the Cemetery & Section select boxes would have to shown (Section being dependent on Cemetery selected). If XYZ Company is selected, then only the Section select box would need to be seen / selected (as the Cemetery is Company specific):
<script>
function getCemetery(val) {
$.ajax({
type: "POST",
url: "get_cemetery.php",
data:'company_name='+val,
success: function(data){
$("#cemetery-list").html(data);
}
});
}
Here is the code of the form:
<body>
<div class="frmDronpDown">
<div class="row">
<label>Company:</label><br/>
<select name="company" id="company-list" class="demoInputBox" onChange="getCemetery(this.value);">
<option value="">Select Company</option>
<?php
foreach($results as $company) {
?>
<option value="<?php echo $company["name"]; ?>"><?php echo $company["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Cemetery:</label><br/>
<select name="cemetery" id="cemetery-list" class="demoInputBox" onChange="getSection(this.value);">
<option value="">Select Cemetery</option>
<?php
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Section:</label><br/>
<select name="section" id="section-list" class="demoInputBox">
<option value="">Select Section</option>
</select>
</div>
</div>
</body>
And here is the additional php code the is called within the script:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["company_name"])) {
if (($_POST["company_name"]<>"None") && ($_POST["company_name"]<>"Other")) {
$sql="SELECT name, available FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$result = mysql_query($sql) or die ( mysql_error());
$row = mysql_fetch_row($result);
$section = $row[0]; // best choice to use if auto fill
$query="SELECT * FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Section</option>';
}else{
$query ="SELECT * FROM cemeteries";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Cemetery</option>';
}
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]." - ".$cemetery["available"]; ?></option>
<?php
}
}
?>
Edit:
Thank you for telling me about .hide and .show. I have looked up examples and what I can find uses a button click. Would you show an example of using them in an php if..else?
Thank you in advance.
Russ
I used the following:
<script>
function wholesection() {
$( "#whole-section" ).slideUp( "fast", function() {
});
}
</script>
AND
echo '<script>',
'wholesection();',
'</script>'
;

Onchange Jquery event condition for dropdown

I am working on a dropdown change event, but I am not able to set a condition for the change event. For the second dropdown(subsel) I want a list of values for which the value in sel is NOT present. So far all I'm able to do is reflect the value in first select dropdown into the second dropdown.
<script>$(document).ready(function() {
$("#sel").live('change', function() {
$("#selsub").val($(this).val());
});
});</script>
<form method="get">
<label for="category">Parent Category</label>
<select name="sel" id="sel">
<?php
include('connection.php');
$query_parent=$query=mysql_query("SELECT * from stations");
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php endwhile;?>
</select>
<br/><br/>
<label>Sub Category</label>
<div class='detail'>
<select name="selsub" id="selsub">
<?php
$query=mysql_query("SELECT * from stations");
while($row1 = mysql_fetch_array($query)): ?>
<option value="<?php echo $row1['name']; ?>"><?php echo $row1['name']; ?></option>
<?php endwhile; ?>
</select>
</div>
Kindly help me to set a condition where in the second dropdown(selsub) all the values would appear except the value one in first dropdown(sel).
Try to do:
$(document).ready(function() {
$("#sel").on('change', function() {
selectedVal = this.value;
$("#selsub option[value='" + selectedVal +"']").hide();
});
});

Search city for selected category

This ps_search.php page has dropdown for categories like laptop, bags etc... and a dropdown for city. if a user wants to post an ad means he/she wants to sell something on website , first of all a category is selected like laptop, bag or anything else. and then city is selected from where the ad is posted. if, for instance, a user posts an ad of laptop from city1 and we have no more ads of laptops from other cities . then after selecting laptop , city 1 should appear in a dropdown menu. i have two files ps_search.php ang get_city.php
//ps_search.php
<form name="search" method="post" action="<?php echo $base_url ?>search_rides.php?go">
<table width="100%" border="0" cellpadding="4" cellspacing="0" id="tbsrch-engine">
<tbody>
<tr>
<td height="61">
<strong>Choose Category:</strong>
</td>
<td>
<select name="category_id" id="category_id" style="width: 155px;" onChange="get_city(this.value,'<?php echo $base_url ?>dropdown/get_city.php')">
<option value="0">Any</option>
<?php $query = "SELECT category_id as id, category_name as name FROM tbl_ps_category ";
$result = mysql_query($query);
?>
<?php while ( $row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['id'].'-'.$row['name']; ?>"><?php echo $row['name']?></option>
<?php }?>
</select>
</td>
</tr>
<tr>
<td height="40">
<strong>City:</strong>
</td>
<td>
<div id="models">
<select name="city_id" id="city_id">
<option value="0">Any</option>
</select>
</div>
</td>
</tr>
<tr>
<td height="32"/>
<td>
<input type="submit" name="button2" id="button2" value="Search an Ad" class="fbutton"/>
</td>
</tr>
</tbody>
</table>
</form>
//get_city.php
<?php
include('../Connections/photohive.php');
$id = $_REQUEST['id'];
$explode = explode('-',$id);
$id = $explode[0];
$sql = "SELECT city_id FROM ".$ps_prefix."product WHERE category_id=".$id;
$query = mysql_query($sql);
//exit;
?>
<select name="city_id" id="city_id" style="width:155px;">
<option value="0">Any</option>
<?php
while ($row = mysql_fetch_array($query)){
$q1= sprintf("Select cityname from tbl_city where city_id='%s'" , mysql_real_escape_string($row['city_id']), " ORDER BY cityoreder ASC");
$r1= mysql_query($q1);
while($row2= mysql_fetch_assoc($r1))
{
?>
<option value="<?php echo $row['city_id']?>"><?php echo $row2['cityname']?></option>
<?php
}
}
?>
</select>
i have included js file as well
<script src="<?php echo $base_url;?>js/jquery.ajaxq-0.0.1.js" type="text/javascript"></script>
Please help me....
Your javascript should look like this:
(function ($) {
// When category select changes
$('#category_id').change(function() {
// make ajax query to get cities
$.get('get_city.php', {id: $(this).val())
.done(function(response) {
// get the cities dropdown from response and insert into page
$('#models').html(response);
});
});
})(jQuery);
I personally don't like returning HTML in my ajax calls. I usually prefer to return a JSON object and then parse out the HTML client side (usually using Handlebars). I think it's cleaner that way.

Categories