$MethodLocationFrom =mysql_query("
SELECT DISTINCT Location_From AS 'locationFrom'
FROM trip
");
echo "<form action='confirmation.php' method='post'>";
echo "<select class = 'LocationFrom' size='1' name='locationFrom' id='locationFrom'>";
while($check = mysql_fetch_array($MethodLocationFrom))
{
echo "<option value='" . $check['locationFrom'] . "'>" . $check['locationFrom'] . "</option>";
}
echo"</select>";
$MethodLocationTo =mysql_query("
SELECT DISTINCT Location_To AS 'locationTo'
FROM trip
");
echo "<select class = 'LocationTo' size='1' size='1' name='locationTo' id='locationTo'>";
while($check = mysql_fetch_array($MethodLocationTo))
{
echo "<option value='" . $check['locationTo'] . "'>" . $check['locationTo'] . "</option>";
}
echo"</select>";
Hi guys! I'm making a shuttle reservation system, I'm having trouble with the option boxes, what I want to do is when I select a place from Location from (first option box) that location would automatically be remove in the location where I want to go (second box) How can I do that?
Ok, let me have a go, with a personal twist
assume the result of iteration to be (reduced for brevity)
<select id="locationFrom">
...
<option value="$from">($from)</option>
</select>
<select id="locationTo">
...
<option value="$to">($to)</option>
</select>
I assume the values of each option-set are the same.
let's get dirty with javascript. Mind you, this is long and has no comments, review it, test it and give me feedback if you find an error.
// script.js
(function(){
var selectFrom, selectTo, unsetChild, nextSibling,
onSelect, removeOption, recoverOption,
loadWin, unloadWin;
onSelect = function () {
var idx = this.selectedIndex;
if (idx !== -1) {
if (unsetChild) {recoverOption();}
removeOption(this.options[idx].value);
}
};
removeOption = function (value) {
unsetChild = selectTo.querySelector('[value="'+value+'"]');
nextSibling = unsetChild.nextSibling;
selectTo.removeChild(unsetChild);
};
recoverOption = function () {
nextSibling
? selectTo.insertBefore(unsetChild,nextSibling)
: selectTo.appendChild(unsetChild);
nextSibling = unsetChild = null;
};
loadWin = function () {
selectFrom = document.getElementById('locationFrom');
selectTo = document.getElementById('locationTo');
selectFrom.addEventListener('change',onSelect,false);
};
unloadWin = function () {
selectFrom.removeEventListener('change',onSelect,false);
selectFrom = selectTo = nextSibling = unsetChild = null;
};
window.addEventListener('load',loadWin,false);
window.addEventListener('unload',unloadWin,false);
});
I've worked out a jQuery solution (tested in Google Chrome):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
function jqyHideSelectedOption(objSelect) {
var strIDSeleted = objSelect.id;
var strID2Handle;
if(strIDSeleted == "locationFrom")
{
strID2Handle = "#locationTo";
}
else
{
strID2Handle = "#locationFrom";
}
strIDSeleted = "#" + strIDSeleted;
//
// show all options: ie, restore default settings.
//
jQuery(strIDSeleted + " option").show();
jQuery(strID2Handle + " option").show();
//
// hide some options in the corresponding select:
//
var selectedCity = jQuery(strIDSeleted).val();
if(jQuery(strID2Handle).val() == selectedCity) {
jQuery(strID2Handle).val(null);
}
jQuery(strID2Handle + " option[value='" + selectedCity + "']").each(function() {
jQuery(this).hide();
});
}
</script>
</head>
<body>
<?php
//
//...
//
$MethodLocationFrom = mysql_query("
SELECT DISTINCT Location_From AS 'locationFrom'
FROM trip
");
echo "<form action='confirmation.php' method='post'>";
echo "<select class = 'LocationFrom' size='1' name='locationFrom' id='locationFrom' onchange='jqyHideSelectedOption(this)'>";
while($check = mysql_fetch_array($MethodLocationFrom))
{
echo "<option value='" . $check['locationFrom'] . "'>" . $check['locationFrom'] . "</option>";
}
echo"</select>";
$MethodLocationTo = mysql_query("
SELECT DISTINCT Location_To AS 'locationTo'
FROM trip
");
echo "<select class = 'LocationTo' size='1' size='1' name='locationTo' id='locationTo' onchange='jqyHideSelectedOption(this)'>";
while($check = mysql_fetch_array($MethodLocationTo))
{
echo "<option value='" . $check['locationTo'] . "'>" . $check['locationTo'] . "</option>";
}
echo"</select>";
//
//...
//
?>
</body>
</html>
For the from city #locationFrom select, an onchange='jqyHideSelectedOption(this)' is used.
When a city is selected in this select, we hide this city name in the list of #locationTo select. If we choose another city, the hidden city is again shown in the destination list, so again available for destination selection.
If a destination is chosen, this city will be hidden in the from cities list.
We don't remove any option from the 2 select's, but rather temprarily hide it, as it's useful if another city is selected, and must be present for customer's selection.
Related
I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.
I am having a trouble with populate a drop-down value from another drop-down with AJAX database. So basically there are Intake and Courses in my form. So, if user choose Intake A, then courses PHP and JQuery will be in Courses option. My problem is now, after i choose Intake A, Courses option doesn't give any value. Can you please help me? Thanks
Here is the AJAX CODE
$(document).ready(function($) {
var list_target_id = 'Courses'; //first select list ID
var list_select_id = 'Iname'; //second select list ID
var initial_target_html = '<option value="">Please select intake...</option>'; //Initial prompt for target select
$('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option
$('#'+list_select_id).change(function(e) {
//Grab the chosen value on first select list change
var selectvalue = $(this).val();
//alert(selectvalue);
//Display 'loading' status in the target select list
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
//Display initial prompt in target select if blank value selected
$('#'+list_target_id).html(initial_target_html);
} else {
//Make AJAX request, using the selected value as the GET
$.ajax({url: 'CoursesDropdown.php?svalue='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
Here is the PHP side
<?php
include "connect.php";
$selectvalue = mysqli_real_escape_string($con, $_GET['svalue']);
$checkuser = "Select Coursesname from courses Where CoursesIntake ='$selectvalue'";
$result2 = mysqli_query($con, $checkuser);
echo '<option value="">Please select...</option>';
echo $result2;
while ($row = mysqli_fetch_array($result2)) {
//echo '<option value=" . $row["CoursesName"] . "> . $row["CoursesName"] . "</option>"';
//echo '<option value=' . $row['Coursesname'] . '>' . $row['Coursesname'] . '</option>';
echo '<option value="">Please select...</option>';
echo '<option value="">Please select...</option>';
}
mysqli_close($con);
?>
I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k
I am have this issue:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do.
The second select list is empty initially.
I want to fill it with values depending of what is chose in first select list.
How can I do that? To fill the second select list only if something is selected in first select list.
MrCode has a nice example for you.
Using Ajax To Populate A Select Box
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with
The best way to handle this would be to populate the list after you made a change on the first list. For example.
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. for example your some.php will take a value parameter. The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}]. Please keep this in mind.
I'm trying to add selected to the option value which is rendered already within the object, but the below is not adding selected to the option value even they are equal. Ignoring the adding selected, is it because after doing this with appending?
eventClick: function(calEvent, jsEvent, view) {
var startFormat = $.fullCalendar.formatDate(calEvent.start, "dd / MM / yyyy");
var form = $("<form id='changeName'>" +
"<h3 class='eventHeader'>Edit Event: " +startFormat+ " </h3>" +
"</div></form>");
form.append("<div class='controls'>" +
"<label class='control-label' for='title'>Language: </label>" +
"<select class='span3' id='lang' name='lang'>" +
<?php foreach($languages as $language): ?>
"<option value='<?=$language->id;?>'><?=$language->title;?></option>" +
<?php endforeach; ?>
"</select>" +
"</div>");
$("#lang option").each(function(){
if ($(this).val() == calEvent.lang)
$(this).attr("selected","selected");
});
}
instead of this:
$(this).attr("selected","selected");
try using .prop():
$(this).prop("selected", true);
Updates:
you can use .done() method and use change event instead:
form.append("<div class='controls'>" +
"<label class='control-label' for='title'>Language: </label>" +
"<select class='span3' id='lang' name='lang'>" +
<?php foreach($languages as $language): ?>
"<option value='<?=$language->id;?>'><?=$language->title;?></option>" +
<?php endforeach; ?>
"</select>" +
"</div>").done(function(){
$(document).on('change', "#lang", function(){
$('option', this).each(function(){
if ($(this).val() == calEvent.lang)
$(this).prop("selected", true);
});
}).change(); //<------fire the change event here when appended in dom
});
this is just an example:
<?php
$array = array('lang1' => 'option1', 'lang2' => 'option2');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<select id="a_select"></select>
<script>
$(function() {
var select_keys = [<?php foreach ($array as $key => $value) {echo "'$key', ";} ?>];
var select_values = [<?php foreach ($array as $value) {echo "'$value', ";} ?>];
$(select_values).each(function(i, item) {
var option = $('<option>'+ item +'</option>');
option.attr('value', select_keys[i]);
$('#a_select').append(option);
});
});
</script>
</body>
</html>
update: key values is added.
you may load this values from another script with ajax, that's gonna be easier & cleaner.