jQuery running the function combobox populate for multiple combobox - javascript

I have combobox
<select name="search_category[]" id="search_category_id">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
<span id="show_sub_categories" align="center">
And here is the JS
jQuery(document).ready(function($){
$('#loader').hide();
$('#show_heading').hide();
$('#search_category_id').change(function(){
$('#show_sub_categories').fadeOut();
$('#loader').show();
$.post("get_chid_categories.php", {
parent_id: $('#search_category_id').val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
});
return false;
});
function finishAjax(id, response){
$('#loader').hide();
$('#show_heading').show();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function alert_id()
{
if($('#sub_category_id').val() == '')
alert('Please select a sub category.');
else
alert($('#sub_category_id').val());
return false;
}
How about if I have multiple combobox with different id?
Example:
<select name="search_category[]" id="search_category_id1">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
<select name="search_category[]" id="search_category_id2">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
I want the function running for that 2 combobox. But when tried to run the code, the function only run for first combobox. (The function is populate second combobox based on first combobox).

You need to load the second select in the $.post.success handler. Example (untested):
$.post("get_chid_categories.php",
{ parent_id: $('#search_category_id1').val() },
function (response){
loadSelect("search_category_id2", response);
}
);
function loadSelect(id, response){
$('#loader').hide();
$('#show_heading').show();
var target = $('#' + id);
target.html(decodeURIComponent(response));
if (!target.is(":visible")) {
target.fadeIn();
}
}

Related

get selected list option from database

i have to get select option list from my database
and for this my controller is
<?php
require_once 'connexion.php';
$sql = "select * from Motif";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die(print_r(sqlsrv_errors() , true));
}
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data["id"] = $row['id'];
$data["libelle"] = utf8_encode($row['libelle']);
echo json_encode($data);
}
echo json_encode($data);
exit;
?>
and my html like this
<select id="rejetselect" class="form-control">
<option value="" selected="selected"></option>
</select>
and to get values from database with ajax i did this code
var $select = $('#rejetselect');
$.ajax({
url: 'motifRejet.php',
dataType: 'json',
data: 'libelle',
success: function() {
alert('good');
},
error: function() {
alert('nooo');
}
});
so after testing all this i can see my alert in good and in my console i can see the information that i got from database but i can't see it in my select option

codeigniter how to populate second dropdown list based on the first one using codeigniter:

I have tried the following but what i need just to populate two dependent drop down (penality_type based on vehicle_type) list:
Is there some one to show me how to implement here please:
This is my Controller:
public function index()
{
$data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
$data['penality_type'] = $this->vehicle_type_model->getAllPenalityType();
$this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}
This is vehicle_type_model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class vehicle_type_model extends CI_Model {
/*
* Get All Vehicle types
*/
public function getAllVtype()
{
$result = $this->db->get('vehicle_type');
return $result->result_array();
}
public function getAllPenalityType()
{
$result = $this->db->get('penality_type');
return $result->result_array();
}
}
This is my View:
<div class="form-group">
<label for="vehicle_type_id">Vehicle Type</label>
<select name="vehicle_type_id" class="form-control vehicle_type_id">
<option value="">Select Vehicle type</option>
</select>
</div>
<div class="form-group">
<label for="penality_type_id">penality type</label>
<select name="penality_type_id" class="form-control penality_type_id">
<option value="">Select penality type</option>
</select>
</div>
What you are doing is incorrect. I assume that your penalty type is dependent on vehicle type, so you should pass vehicle_type id through ajax to the controller, then to your database and load them into the penalty type drop-down.
Please refer below code
Your index function will have just this,
public function index()
{
$data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
$this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}
Your view
<div class="form-group">
<label for="vehicle_type_id">Vehicle Type</label>
<select name="vehicle_type" class="form-control vehicle_type_id" id = "vehicle_type">
<option value="">Select Vehicle type</option>
<?php foreach($vehicle_type as $row) { ?>
<option value="<?php echo $row->vehicle_type_id ?>"><?php echo $row->vehicle_type_name; ?></option>
<?php } ?>
</select>
</div>
AJAX Code
var base_url = "<?php echo base_url; ?>";
$("#vehicle_type").change(function () {
if ($('#vehicle_type').val() != "") {
$.ajax({
url: base_url + "your_controller/get_penality_by_id",
type: 'POST',
cache: false,
data: {
'vehicle_type_id': $('#vehicle_type').val()
},
success: function (data) {
if($data){
$("#penality_type").html(data);
}
}
});
}
});
Controller
public function get_penality_by_id(){
$vehicle_type_id = $this->input->post('vehicle_type_id');
$data = array('vehicle_type_id' => $vehicle_type_id);
$result = $this->your_model_name->get_penality($data);
if($result){
$option = "<option value=''>--Select an Option--</option>";
foreach ($result as $row){
$option .= "<option value='".$row->penality_id."'>".$row->penality_name."</option>";
}
echo $option;
}else{
echo $option = "<option value=''>--Select an Option--</option>";
}
}
Model
public function get_penality($data){
$this->db->select('*');
$this->db->from('table-name');
$this->db->where($data);
$result_set = $this->db->get();
if($result_set->num_rows() > 0){
return $result_set->result();
}
else {
return FALSE;
}
}
Please note that your vehicle type drop-down option will have the vehicle_type id, which can be used for fetching your dependent penalty. Hope this can help you.

MySQL table populating one dropsown. Upon selection, A second dropdown is populated

Ok, so I've checked the net and the other questions on here and I'm stumped. I've tried a javascript solution from a question posted on here but I think it's not liking MySQL populating the <option>s. I'll copy all the code I've got including the javascript I have.
SCRIPT:
<script>
$(function() {
$('#groups').on('change', function() {
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function() {
if (
$(this).attr('data-group') === val || $(this).attr('data-group') === 'SHOW'
) {
$(this).show();
} else {
$(this).hide();
}
});
});
$('#groups').trigger('change');
});
</script>
PHP 1st dropdown:
<select class="form-control" id="groups">
<?php
$sql = "SELECT BoilerBrand FROM boilerbrands";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['ID']."'>".$row['BoilerBrand']."</option>";
}
?>
</select>
PHP 2nd dropdown
<select class="form-control" id="sub_groups">
<option data-group='SHOW' value="0">Model</option>
<?php
$sql = "SELECT * FROM boilermodels";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option data-group='".$row['BoilerBrand']."' value='".$row['BoilerGC']."'>".$row['BoilerModel']."</option>";
}
?>
</select>
Any help with this would be greatly appreciated!
Thanks :)
The way I normally do this is instead of hiding/showing the options I remove/add them. I believe if you hide the options then the select input can still have that value.
SCRIPT:
<script>
$(function(){
<?php
$sql = "SELECT * FROM boilermodels";
$result = mysql_query($sql);
$models = array();
while ($row = mysql_fetch_array($result)) {
$models[$row['BoilerBrand']][] = $row;
}
/* should look like
$models = [];
$models[1][] = ['ModelID'=>'1','BoilerBrand'=>'1','BoilerModel'=>'240E','BoilerGC'=>'47-777-77','BoilerImage'=>'47-777-77.jpg' ];
$models[1][] = ['ModelID'=>'3','BoilerBrand'=>'1','BoilerModel'=>'290D','BoilerGC'=>'11-111-11','BoilerImage'=>'11-111-11.jpg' ];
$models[2][]= ['ModelID'=>'2','BoilerBrand'=>'2','BoilerModel'=>'250E','BoilerGC'=>'47-777-77','BoilerImage'=>'47-777-77.jpg' ];
*/
?>
var _boilermodels = '<?php echo json_encode($models); ?>';
var jsonBoilerModels = JSON.parse(_boilermodels);
console.log(jsonBoilerModels);
$('#groups').on('change', function(){
var $this = $(this);
var val = $this.val();
var sub = $('#sub_groups');
sub.find('option').remove();
var appendList = [];
$.each(jsonBoilerModels[val],function(key,value){
appendList.push('<option value="'.concat(value['BoilerGC'], '">', value['BoilerModel'], '</option>'));
});
sub.append(appendList);
});
$('#groups').trigger('change');
});
</script>
1st Dropdown:
<select class="form-control" id="groups">
<?php
$sql = "SELECT ID ,BoilerBrand FROM boilerbrands";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['ID']."'>".$row['BoilerBrand']."</option>";
}
?>
</select>
2nd Dropdown:
<select class="form-control" id="sub_groups">
<option value="">Select A Model</option>
</select>

How to Hide and Show OPTIONS of a dropdown with JQuery in IE

So i have tried this to get it working. It works fine on Firefox and Chrome but doesn't work on IE as always. My idea about the Javascript function was i look in the first option box and look when it get changed. When changed it should grab the value of the the option box and look for it in the second one. Then display just the Optionswith the same value.
The PHP code :
<label style="width:100px;float:left;">für das Revier:*</label>
<select class="required" id="reviernummer" style="width:240px;"name="verhaltenscode" ' >
<?php $selected = $arrayAktuellerDatensatz['verhaltenscode'];?>
<option selected ="selected" value="<?php echo $selected; ?>"><?php echo $selected; ?></option>
<?php loadselect('kataster', 'Fischereibuchzahl', 'Fischereibuchzahl');?>
</select><br />
<select class="required" id="verhaltenscode" style="width:240px;" name="verhaltenscode">
<?php $selected = $arrayAktuellerDatensatz['verhaltenscode_neu'];?>
<option selected ="selected" value="<?php echo $selected; ?>"><?php echo $selected; ?></option>
<?php loadselect('helpbrutstatus', 'Brutstatus', 'Brutstatus');?>
loadselect function:
if ($tblname == 'kataster'){
$query = "SELECT * FROM kataster";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fieldvalue = $row['Fischereibuchzahl'];
$fieldcaption = $row['Fischereibuchzahl'];
$lat = $row['Benennung']?>
<option title="<?php echo $lat; ?>" value="<?php echo $fieldvalue;?>"><?php echo $fieldcaption .' | '.$lat?></option> <?php
}
}
else if ($tblname == 'helpbrutstatus'){
$query = "SELECT * FROM helpbrutstatus" ;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fieldvalue = $row['Fischereibuchzahl'];
$status = $row['Fischereibuchzahl'];
$fieldcaption = $row['Brutstatus']; ?>
<option value="<?php echo $fieldvalue;?>" title="<?php echo $status;?>" class="sorted">
<?php echo $status." | ".$fieldcaption?></option> <?php
}
}
Javascript function:
reviernummer.onchange = function() {
var look = $("#reviernummer").val();
$("option[class='sorted']").each(function(index, val) {
if ($(this).is('option') && (!$(this).parent().is('span')))
$(this).wrap((navigator.appName == 'Microsoft Internet Explorer') ? '<span>' : null).hide();
});
$("option[title='" + look + "']").each(function(index, val) {
if (navigator.appName == 'Microsoft Internet Explorer') {
if (this.nodeName.toUpperCase() === 'OPTION') {
var span = $(this).parent();
var opt = this;
if ($(this).parent().is('span')) {
$(opt).show();
$(span).replaceWith(opt);
}
}
} else {
$(this).show(); //all other browsers use standard .show()
}
});
};

How hide select dropdown based value from another dropdown

Why my script doesn't work? I need to hide the sem dropdown when branch dropdown is select ALL. I try script below but it doesn't work.
And this is my script
<script>
$(document).ready(function () {
$('#branch').change(function () {
if (this.value != "ALL") {
$('#sem').show();
} else {
$('#sem').hide();
}
});
});
</script>
</head>
<body onload=showCourses(str="ALL")>
<select name="branch" id="branch" onchange="showCourses()">
<option value="ALL" selected='ALL'>ALL</option>
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT * FROM app GROUP BY app_cn ORDER BY app_cn");
while($row = $result->fetch_assoc())
{
echo '<option value="'.$row['app_cn'].'">'.$row['app_cn'].'</option>';
}?>
</select>
<select name="sem" id="sem" onchange="showCourses()">
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT * FROM app GROUP BY app_plan_no ORDER BY app_plan_no");
while($row = $result->fetch_assoc())
{
echo '<option value="'.$row['app_plan_no'].'">'.$row['app_plan_no'].'</option>';
}?>
</select>
check for this in if statement:
$('option:selected', this).val()

Categories

Resources