Remove a drop down item if it is selected - php

I have multiple instances of select drop downs on a form, eight to be exact. If I select a number on the first select drop down I want to hide the selected number from the second select drop down up to eighth.
For the purpose of this I will only show two of the eight select drop downs.
View Code -
Select drop down one -
<div class="col-xs-12 col-sm-3">
<div class="form-group">
<?php echo Form::label('test_id', 'Test', array('class' => 'col-xs-3 control-label')) ?>
<div class="col-xs-9">
<select name="test_id" id="test_id" class="form-control select2" data-placeholder="Select...">
<option value=""></option>
<?php foreach (ORM::factory('Test')->order_by('id')->find_all() as $row) : ?>
<option value="<?php echo $row->id ?>"
<?php if ($b->id == $row->id) echo 'selected="selected"' ?>>
<?php echo $row->id ?></option>
<?php endforeach ?>
</select>
</div>
</div>
Select drop down two-
<div class="col-xs-12 col-sm-3">
<div class="form-group">
<?php echo Form::label('test_id', 'Test', array('class' => 'col-xs-3 control-label')) ?>
<div class="col-xs-9">
<select name="test_id" id="test_id" class="form-control select2" data-placeholder="Select...">
<option value=""></option>
<?php foreach (ORM::factory('Test')->order_by('id')->find_all() as $row) : ?>
<option value="<?php echo $row->id ?>"
<?php if ($b->id == $row->id) echo 'selected="selected"' ?>>
<?php echo $row->id ?></option>
<?php endforeach ?>
</select>
</div>
</div>
jQuery Code -
var $selects = $('select');
$('select').change(function () {
$('option:hidden', $selects).each(function () {
var self = this,
toShow = true;
$selects.not($(this).parent()).each(function () {
if (self.value == this.value) toShow = false;
})
if (toShow) $(this).show();
});
if (this.value != "") //to keep default option available
$selects.not(this).children('option[value=' + this.value + ']').hide();
});
This does not work in the slightest.
Any help would be appreciated.
Cheers

This won't work with select2 and hidden options. You can work around this by disabling the options and a bit of CSS to hide them. See below:
JS
$(document).ready(function () {
var $selects = $('select');
$selects.select2();
$('select').change(function () {
$('option:hidden', $selects).each(function () {
var self = this,
toShow = true;
$selects.not($(this).parent()).each(function () {
if (self.value == this.value) toShow = false;
})
if (toShow) {
$(this).removeAttr('disabled');
$(this).parent().select2();
}
});
if (this.value != "") {
$selects.not(this).children('option[value=' + this.value + ']').attr('disabled', 'disabled');
$selects.select2();
}
});
})
CSS
.select2-results .select2-disabled {
display:none;
}
Working example here: http://jsfiddle.net/10nwqwck/4/

Something like this might work :
$(".select").click(function () {
var value = $(this).val();
// to hide every option that have the selected value
$("option").filter(function() {
return $(this).val() == value;
}).hide();
// to show the option currently selected in the current list
$(this).find("option").each(function () {
if ($(this).val() == value)
{
$(this).show();
}
});
});
Hope this help.

$("#Select_id").blur(function () {
var value = $(this).val();
alert($("#Select_id").val() == value);
// to hide every option that have the selected value
if ($("#Select_id").val() == value) {
$("#Option_id"+value).hide();
}
});
Try this
you can remove the selected item from the drop doen like this simply. dropdown id is 'Select_id' and selected option id need to be 'Option_id'. if not equel both then selected option will be remove

Cheers Vlad, that worked mate.
To make the jQuery more optimized, this was done.
$(document).ready(function () {
var $selects = $('select');
$selects.select2();
$('select').change(function () {
$('option:hidden', $selects).each(function () {
var self = this,
toShow = true;
$selects.not($(this).parent()).each(function () {
if (self.value == this.value) toShow = false;
})
if (toShow) {
$(this).removeAttr('disabled');
}
});
if (this.value != "") {
$selects.not(this).children('option[value=' + this.value + ']').attr('disabled', 'disabled');
}
});
})
Thank you for your help :)

Related

One dropdown down depends on two dropdowns in codeigniter with

Here I have Two independent dropdowns : "Sub company " and " Role" and there is a third dropdown which depends on these two dropdowns. basically what I want to implement is if the chosen "Role" is NOT 'manager' and 'admin', then displays third dropdown "manager", which its options depends on sub company .
Right now I am able to get all the managers depends on sub company , what I need to do is to make a condition to only show managers list when role !== 'manager' && role !== 'admin'.
Here is the view.php
<div class="form-group col-md-4">
<label for="pwd">Sub Company Name</label>
<div class="alert-danger"><?php echo form_error('Subcom'); ?></div>
<select class="form-control" id="Subcom" name="Subcom" >
<option value="">Select Sub Company</option>
<?php
foreach($company_name as $row )
{
echo '<option value="'.$row->company_name.'" '.set_select('Subcom', $row->company_name).'>'.$row->company_name.'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="pwd">Role</label>
<div class="alert-danger"> <?php echo form_error('role'); ?></div>
<select class="form-control" id="role" name="role" placeholder="Select Role">
<option value="">Select Role</option></div>
<?php
foreach($role_name as $row )
{
echo '<option value="'.$row->id.'" '.set_select('role', $row->role_name).'>'.$row->role_name.'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-4" >
<label for="pwd">Manager</label>
<div class="alert-danger"> <?php echo form_error('manager'); ?></div>
<select class="form-control" id="manager" name="manager" placeholder="Select Manager" style="display:none" disabled>
<option value="">Select Manager</option>
</select>
</div>
And here is the script
<script type="text/javascript">
$(document).ready(function(){
$(' #Subcom, #role').on('change' , function() {
var company_name = $('#Subcom').val();
var role = $('#role').val();
if( company_name!==''&& role !== '' && role !=='manager' && role !==
'admin')
{
//alert('ok');
$('#manager').prop('disabled', false);
$.ajax({
url:"<?php echo base_url()?>getManager",
type: "POST",
data: { 'company_name' : company_name},
dataType:'json',
success: function(data){
console.log(data);
false;
$('#manager').html(data.manager);
$('#manager').show();
},
error: function(event){
console.log(event);
alert('Error occur...');
}
});
}else {
//alert('sgsg');
$('#manager').prop('disabled', true);
$('#manager').hide();
}
});
});
</script>
Here is the controller
public function getManager()
{
//echo json_encode ($_REQUEST); die;
//print_r($_REQUEST);
//die;
$company_name = $this->input->post('company_name');
$getallmanager = $this->project_model->get_manager_query($company_name);
$getallstaff = $this->project_model->get_all_staff($company_name);
$all_the_mangers = '';
$all_the_staffs = '';
if(count($getallmanager)>0)
{
foreach ($getallmanager as $manager){
//if(role!=='manager')
$all_the_mangers .='<option value="' .$manager->first_name.'">'.$manager->first_name.'</option>';
}
}
if(count($getallstaff)>0)
{
foreach ($getallstaff as $staff){
$all_the_staffs .='<option value="' .$staff->first_name.'">'.$staff->first_name.'</option>';
}
}
$result = array('manager'=>$all_the_mangers,'staffs'=>$all_the_staffs);
echo json_encode($result);die;
}
}
And here is the Model:
public function get_manager_query($company_name)
{
$query = $this->db->get_where('user_login', array('company_name' => $company_name,'role'=>'manager'));
return $query->result();
}
public function get_all_staff($company_name)
{
$query = $this->db->get_where('user_login', array('company_name' => $company_name,'role !='=>'manager'));
return $query->result();
}
it is simply pass a var to show or hide.
in your controller file pass data['role_admin'] = 1;
in your view file
if($role_admin==1){
// show your Manager code
}
Add style="display:none" and disabled to manager select so it won't show up at load. Also selects don't need a value, if you want to set a specific option than you need to do it in the loops like this:
foreach($company_name as $row )
{
echo '<option value="'.$row->company_name.'" '.set_select('Subcom', $row->company_name).'>'.$row->company_name.'</option>';
}
Also it would be a good idea to move the form errors before the select and not wrap the options with it.
<script type="text/javascript">
$(document).ready(function(){
$('#Subcom,#role').on('change' , function() {
var company_name = $('#Subcom').val();
var role_name = $('#role').val();
if(company_name !== '' && role_name !== 'manager' && role_name !== 'admin')
{
$('#manager' ).prop('disabled', false);
$.ajax({
url:"<?php echo base_url()?>getManager",
type: "POST",
data: { 'company_name' : company_name},
dataType:'json',
success: function(data){
//alert('ok');
console.log(data);
$('#manager').html(data.manager);
$('#manager').show();
},
error: function(event){
console.log(event);
alert('Error occur...');
}
});
}
else
{
$('#manager').prop('disabled', true);
$('#manager').hide();
}
});
});
</script>
EDIT: for future reference here's the final code
https://jsfiddle.net/Lo50z6q8/

Multiple else if in jQuery

I am doing dependent select box using jquery, ajax and php from same table of the database. Testpage
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "name") {
result = 'category';
alert ('test1');
} else if (action == "category") {
result = 'material';
alert ('test2');
} else if (action == "material") {
result = 'source_light';
alert ('test3');
} else if (action == "source_light") {
result = 'color_temperature';
alert ('test4');
} else {
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
I don't know why but it only works: test1 and test2. Test3 and 4 are not sent to php.
HTML file
Maybe something is wrong with select box? But these are just a select box with id's.
<select name="name" id="name" class="form-control action">
<option value="">Select name</option>
<?php echo $name; ?>
</select>
<br />
<select name="category" id="category" class="form-control action">
<option value="">Select category</option>
</select>
<br />
<select name="material" id="material" class="form-control">
<option value="">Select material</option>
</select>
<br />
<select name="source_light" id="source_light" class="form-control">
<option value="">Select source_light</option>
</select>
<br />
<select name="color_temperature" id="color_temperature" class="form-control">
<option value="">Select color_temperature</option>
</select>
What about something like this
$(document).ready(function(){
$('.action').change(function()
{
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
switch(action) {
case "name":
result = 'category';
alert ('test1');
break;
case "category":
result = 'material';
alert ('test2');
break;
case "material":
result = 'source_light';
alert ('test3');
break;
case "source_light":
result = 'color_temperature';
alert ('test4');
break;
default:
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
Verify your drop down list under "action" class. As per your condition it won't trigger if your selected drop down item doesn't have value if($(this).val() != '').
Also make sure your expected drop down items have the value material for your test3 and source_light for your test4
Another suggestion: To load and trigger dynamic change event for drop down you can use below jQuery API:
$(document).on("change", ".action", function(){
//Your code here
});
If this doesn't solve your problem then please share your HTML or drop down data.
Updated answer: I can see there is no class "action" in your select/drop down items for material, source_light and color_temperature. That is why change actions of these drop down items are not catching in your $('.action').change(function() ... code block.

Dependent Dropdown and Input not getting populated (Codeigniter, Ajax, jQuery)

I will try the cascading dependent select box and input in Codeigniter with Ajax. The first step works quite well. The Securities can be easily loaded, when selecting an Account. The problem starts with the second step. So, when I try after the Security-selection to set the appropriate changeable Inputs, the Security-select will getting blocked and then nothing works. Don't understand what the problem is.
Please help me, the nasty blockage to dissolve. Thanks.
Ajax:
$(document).ready(function(){
var _form = $("#trans_form").serializeArray();
$('#amount_section').hide();
$('#quantity_section').hide();
$('#accountDrop').on('change',function(){
$("#securityDrop > option").remove();
var accountID = $(this).val();
if(accountID == '#') {return false;}
$.ajax({
data: _form,
type: "POST",
url: global_base_url + "custody/get_securities_dropdown/" + accountID,
success: function(securities) {
$.each(securities,function(id,value) {
var opt = $('<option />');
opt.val(id);
opt.text(value);
$('#securityDrop').append(opt);
});
}
});
});
$('#securityDrop').on('change',function(){
$('#amount_section').hide();
$('#quantity_section').hide();
var securityID = $(this).val();
if(securityID == '#') {return false;}
$.ajax({
data: _form,
type: "POST",
url: global_base_url + "custody/get_security_unit_ajax/" + securityID,
success: function(securUnit) {
if (securUnit == "UNIT") {
$('#quantity_section').show(300);
};
else if (securUnit == "FAMT") {
$('#amount_section').show(300);
};
}
});
});
});
Controller:
public function get_securities_dropdown($account_id){
$securities = $this->custody_model->get_security_by_account($account_id);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($securities);
}
public function get_security_unit_ajax($security_id){
$securUnit = $this->custody_model->get_security_unit($security_id);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($securUnit);
}
Model:
public function get_accounts_dropdown(){
$accounts = $this->db->select("ID as id, Account_Desc as descr")
->order_by("descr", "ASC")
->get($this->table2)->result();
$accounts_arr;
$accounts_arr['#'] = '-- Please select Account --';
foreach ($accounts as $account) {
$accounts_arr[$account->id] = $account->descr;
}
return $accounts_arr;
}
public function get_security_by_account($account_id){
if(!is_null($account_id)){
$securities = $this->db->where("a.ID_Account", $account_id)
->select("b.ID as id, b.Security_Desc as descr")
->join($this->table5 . " as b", "b.ID = a.ID_Security")
->order_by("descr", "ASC")
->get($this->table6 . " as a");
if($securities->num_rows() > 0){
$securities_arr;
foreach ($securities->result() as $security) {
$securities_arr[$security->id] = $security->descr;
}
return $securities_arr;
}
}
return;
}
View:
<?php echo form_open_multipart(site_url("custody/add_transaction_pro"), array("id" => "trans_form")) ?>
<div>
<label for="accountDrop">Account</label>
<div>
<?php echo form_dropdown('accountDrop', $account_arr, '#', 'id="accountDrop"'); ?>
</div>
</div>
<div id="security_section">
<label for="security_select">Security</label>
<div>
<select name="securityDrop" class="required" id="securityDrop">
<option value="#">-- Please select Security --</option>
</select>
</div>
</div>
<div id="quantity_section">
<label for="quantity">Quantity</label>
<div id="quantityInput">
<input type="text" id="quantity" name="quantity">
</div>
</div>
<div id="amount_section">
<label for="settl_amount">Amount</label>
<div id="amountInput">
<input type="text" id="settl_amount" name="settl_amount">
</div>
</div>
I have solved it. The error was quite simple, the unnecessary semicolons in the ajax part. The syntax is if() { } else if{ }

Change select dropdown based on first select dropdown?

I am trying to change the second select dropdown based on whether the first selected option contains an (m) or (ft).
My form HTML search is as follows:
<form id="search" action="/property_search" method="get" class="clearfix">
<select name="sqsize" id="sqsize" class="sqsize">
<option value="">sq.ft/sq.m:</option>
<option value="233.52m">233.52m</option>
<option value="233.52m">233.52m</option>
<option value="467.04m">467.04m</option>
<option value="2,513ft">2,513ft</option>
<option value="2,513ft">2,513ft</option>
<option value="5,026ft">5,026ft</option>
</select>
<select name="sqsizemin" id="sqsizemin" class="sqsizemin">
<option value="">Size Min:</option>
</select>
<input type="submit" class="submit" value="Search">
</form>
My Jquery is as follows:
<script type="text/javascript">
$(function(){
$('#sqsize').change(function () {
var options = '';
if($(this).val() == 'm') {
options = '<option value=""></option>';
}
else if ($(this).val() == 'ft') {
options = '<option value="6">6</option>';
}
$('#sqsizemin').html(options);
});
$('#sqsize').trigger('change');
});
Try something like this(using indexOf):
$(function(){
$("#sqsize").change(function(){
var options = '';
if($(this).val().indexOf('m') > -1) {
options = '<option value="">mm</option>';
}
else if ($(this).val().indexOf('ft') > -1) {
options = '<option value="6">6</option>';
}
$('#sqsizemin').html(options);
});
});
Working fiddle: https://jsfiddle.net/robertrozas/b0w61quf/
Try like this:
https://jsfiddle.net/kc5qqtco/
$(function(){
$('#sqsize').change(function () {
if($(this).val().match(/m/g)) {
$('<option value=""></option>').appendTo('#sqsizemin');
}
else if ($(this).val().match(/ft/g)) {
$('<option value="6">6</option>').appendTo('#sqsizemin');
}
});
});
Using indexOf will get you a working solution.
See the jsfiddle

Populate the last selectbox based on the first

I tried to populate a select box based on the first but no result, no error but the second select box is not populate:
My html:
<div class="form-group">
<label>Firm:</label>
<select class="form-control marg-left-10" id="firm">
<?php if($all_firms): ?>
<?php foreach($all_firms as $firm): ?>
<option value="<?php echo $firm['id_firm']; ?>"><?php echo $firm['name_firm']; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
<div class="form-group">
<label>Administrator</label>
<select class="form-control marg-left-10" id="admin">
</select>
</div>
My php:
public function getAllFirms()
{
$this->load->database();
$all_firms = $this->db->query("SELECT *FROM firms");
if ($all_firms->num_rows())
{
$all_firms = $all_firms->result_array();
}
else
{
$all_firms = NULL;
}
return $all_firms;
}
public function getAdministrator($id)
{
$this->load->database();
$get_admin = $this->db->query("SELECT * FROM users,firms WHERE firms.id_firm = users.fk_firm and users.id = $id");
if ($get_admin->num_rows())
{
$get_admin = $get_admin->result_array();
}
else
{
$get_admin = NULL;
}
return $get_admin;
}
My script:
$("#firm").change(function() {
var selectedMark = $("#firm").val();
if (selectedMark != "") {
$.ajax({
type: "GET",
url: "<?php echo base_url() . 'user/getAdministrator'; ?>" + selectedMark,
success: function(data) {
$("#admin").html("");
$("#admin").append("<option value=''></option>");
$.each(data, function() {
$("#admin").append("<option value='" + this.id + "'>" + this.name + "</option>");
});
}
});
}
});
I use CodeIgniter as backend language, the first selectt box is populated but the second not.Please help me guys...HELP please!!!!! HELP ME GUYS!!Another idea to resolve this?
it looks like you've forgotten to add # when you calling 'admin' select. I.e. see 'success' section of your JS and change:
$('admin')...
to
$('#admin')...
you are looking like this:
<div class="form-group">
<label>Firm:</label>
<select class="form-control marg-left-10" id="firm">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="form-group">
<label>Administrator</label>
<select class="form-control marg-left-10" id="admin"></select>
</div>
<script>
$("#firm").change(function() {
var selectedMark = $("#firm option:selected").val();
var selectedMarkt = $("#firm option:selected").text();
if (selectedMark != "") {
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
$("#admin").append("<option value='" + selectedMark + "'>" + selectedMarkt + "</option>");
}
});
}
});
</script>
Looks like you need another "/" on this line:
url: "<?php echo base_url() . 'user/getAdministrator'; ?>" + selectedMark,
Right after 'user/getAdministrator'.

Categories