Having difficulty getting this to work. Using Chrome javascript console, I can see that my function is firing and getting the result I nee, it just won't populate the multiple select. Here's the code:
jQuery:
$("select[name='field[one]']").change(function()
{
var optionValue = $("select[name='field[one]']").val();
$.get
('/directory/location/getData', {select:optionValue},
function(data)
{
$("select[name='subjects']").val(data);
}
);
}
);
HTML:
<select name="field[one]" id="field_one">
<option value="" selected="selected"></option>
<option value="2011">2011</option>
</select>
<select multiple id="show_results" name="subjects" />
</select>
AJAX PHP Call:
public function executeGetData(sfWebRequest $request){
$year = $request->getParameterHolder()->get('select');
$specialties = Doctrine_Core::getTable('Specialty')->getSpecialtyArray();
$array = array();
foreach($specialties as $specialty){
$array[$specialty['id']] = '';
$count = Doctrine_Core::getTable('HistoricalSalaries')->getCountPerSpec($year, $specialty['id']);
$array[$specialty['id']] .= $specialty['name']." Count($count)";
}
return $this->renderText( json_encode( $array ) );
}
The result is a json encoded array... which I think is the problem... getting the multiple select to interpret that info correctly. Currently nothing happens after the call is made and the data retrieved.
Here is a sample of the json encoded array result shown in chrome debugger:
{
2: "Aerospace Medicine Count(50)",
3: "Abdominal Radiology (DR) Count(65)",
4: "Addiction Psychiatry (P) Count(46)",
5: "Adolescent Medicine (PD) Count(23)"
}
Thanks in advance.
You can do this:
function(data) {
$.each(data, function(index, itemData) {
var newOption = "<option value='" + index + "'>" + itemData + "</option";
$("#show_results").append(newOption);
});
}
Here's a fiddle that demo's looping over the JSON: http://jsfiddle.net/tymeJV/8eUFe/
Here's a fiddle demoing your problem: http://jsfiddle.net/tymeJV/8eUFe/1/
Related
Want to make a php program, where there will be a drop down which will contain some name of brands .. after selecting the " first drop down/ brands" products of the selected brand will show on another drop down.. need help . anyone ?
What you looking for is called a dependent select. It have barely nothing to do with php (except populating select options). I've found a demo for your case. You will need to install jquery to implement it in your code.
var $city = $(".city").on('change', function() {
$city.not(this).get(0).selectedIndex = this.selectedIndex;
});
You need to read about jQuery or CSS.
Look at this example (jQuery): http://dev7studios.com/dropit/
so you have to use ajax to do this
$(document).on("change","first select box",function(){
var id = $("first select box").val();
$.ajax({
url: "path to your file where you should write db code",
type: "POST",
dataType: "HTML",
async: false,
data: {"id": id},
success: function(data) {
$("second select box").html(data);
// here directly manipulate the data in controller or get the data in success function and manipulate .
}
});
})
in the file where you write db code
$a = "";
foreach(rows fro db as $a){
$a .= "<select value='db id'><?= name ?></select>";
}
echo $a;
we are capturing $a to out normal file add making that as the value for our second select box.
Hope it hlps
Use javascript function onchange select element and fetch records according to selected first select element value.
<form name="product" method="post" >
<select id="category" name="category" onChange="relodme()">
<option value=''></option>
<?php
$qry = "select * from category order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['category_id']?>" <? if($_POST['category'] == $arr['category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
<select id="Type" name="Type" >
<option value=''></option>
<?php
$qry = "select * from subcategory where category_id = '".$_POST['category']."' order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['sub_category_id']?>" <? if($_POST['Type'] == $arr['sub_category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
</form>
Javascript function:
function relodme()
{
document.forms[0].action="test1.php"; //your page name give here....
document.forms[0].submit();
}
I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.
I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.
I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>
I have a Select box and a text box to search through the list in the select box. The Select box is getting populated from a database with PHP. What I am trying to achieve here is as soon as clear the text field; the select box should refresh. I have to reload the whole page to do that. Here is the little script that I using to search through select box.
function filterSelectBox(filterButton) {
var searchValue = document.getElementById('selectFilter').value.toLowerCase();
var selectField = document.getElementById("domainID");
var optionsLength = selectField.options.length;
for(var i = 0; i < optionsLength; i++) {
if(selectField.options[i].innerHTML.toLowerCase().indexOf(searchValue) >= 0) {
selectField.options[i].style.display = 'block';
} else {
selectField.options[i].style.display = 'none';
}
}
}
Here is HTML Elements associated with the code.
<div class="search_domains" id="search_domains">
<input type="text" id="selectFilter" name="selectFilter" />
<input type="button" id="filterButton" value="Filter" onClick="filterSelectBox(this)"/>
</div>
and this is how I am populating the Select box,
<select name="domainID" id="domainID" size="15" style="width:175">
<option>Select a Domain</option>
<? foreach ($domains as $row) {
?>
<option value="<?=$row -> id ?>"><?=$row -> domain ?></option>
<? } ?>
</select>
Put this code:
document.getElementById('selectFilter').onkeyup = function() {
if(this.value.length == 0) {
var selectField = document.getElementById("domainID");
var optionsLength = selectField.options.length;
for(var i = 0; i < optionsLength; i++) {
selectField.options[i].style.display = 'block';
}
}
};
just before the </body> tag in your page, and it will show all of the options when you clear the textbox value.
What I'd do here is populate the list with AJAX from that same PHP file, but have it output JSON. On loading the page, the AJAX request would load the php file, get the JSON and add the items in the list.
For refreshing when the text field is blank, you could use an onChange or onKeyUp and check the length of the value.
I think all this would be much simpler in jQuery or any JS framework than pure JS :)
These will help:
http://css-tricks.com/dynamic-dropdowns/
Using jQuery, JSON and AJAX to populate a drop down
Populate dropdown using json
Populate Dropdown Menu in PHP from JSON
You could definitely use AJAX, but for this example, it may not be necessary. It might be more efficient to just store the original contents in a Javascript array and reset it when you need to. I would actually remove the options instead of hiding them:
<script type="text/Javascript">
var originalOptions = {<?php $echo = array(); foreach ($domains as $row) $echo[] = "\"{$row->id}\":\"{$row->domain}\""; echo implode(", ", $echo); ?>};
function filterSelectBox(text)
{
var selectField = document.getElementById('domainID');
selectField.options.length = 0;
for (var key in originalOptions)
{
if (originalOptions[key].substr(0, text.length) == text)
{
var option = document.createElement("option");
option.value = key;
option.text = originalOptions[key];
selectField.add(option, null);
}
}
}
</script>
<select name="domainID" id="domainID" size="15" style="width:175">
<?php foreach ($domains as $row) {
echo "\t<option value=\"{$row->id}\">{$row->domain}</option>\n";
} ?>
</select>
<input type="text" onkeyup="filterSelectBox(this.value)" />