JQuery to populate select list based on another select list - javascript

I have 2 selects, one for states and one for cities, when the user selects the state the cities dropdown must be populated.
It seems it is working fine, when selecting the state you can see how the select is populated and you can select a city, however, if I revise the source code for the html I can not see any code (RMB View source code) and the selected value is not send to process the form.
My HTML
<select name="state" id="state" >
<option value="1">State One</option>
<option value="2">State Two</option>
<option value="3">State Three</option>
</select>
<select name="city" id="city">
</select>
My JQuery (Got from a tutorial and adapted)
$(document).ready(function($) {
var list_target_id = 'city';
var list_select_id = 'state';
var initial_target_html = '';
$('#'+list_select_id).change(function(e) {
var selectvalue = $(this).val();
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
$('#'+list_target_id).html(initial_target_html);
} else {
$.ajax({url: 'cities.php?idc='+selectvalue,
success: function(output) {
//alert(selectvalue);
$('#'+list_target_id).html(output);
}});
}
});
});
The cities.php (here I read data from a DB, however, here is a simple example)
<?
//these are the city values
echo '<option value="0">Select...</option>';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
?>
Any ideas whats wrong? I can not get the values from cities.
Any help... thank you!

Just serialize and open the URL to process the form:
$(document).ready(function($) {
$('#submit').click(function(evt){
evt.preventDefault();
window.location.href = 'processTheForm.php?'+$('#myForm').serialize();
})
var list_target_id = 'city';
var list_select_id = 'state';
var initial_target_html = '';
$('#'+list_select_id).change(function(e) {
var selectvalue = $(this).val();
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
$('#'+list_target_id).html(initial_target_html);
} else {
$.ajax({url: 'cities.php?idc='+selectvalue,
success: function(output) {
//alert(selectvalue);
$('#'+list_target_id).html(output);
}});
}
});
});

Related

I'm trying to do dynamic dropdown but it seems that ajax is not working/running

I'm trying to do a dynamic dropdown with my form with Philippine locations, it goes like this choose city -> then barangay data will show up depends on what city you chose.
I have a problem with running ajax, it seems like the moment it reaches $ajax it stops there.
I've already tried alert (city) before if (city) and within if (city) and it works, the alert shows.
I tried putting alert(city) or alert(error) within ajax but nothing showed up, so I concluded that ajax is not running at all (unless my syntax is wrong)
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-field col s6">
<select name="barangay" id="barangay">
<option value="" disabled selected>Choose a Barangay</option>
</select>
<label for="barangay">Barangay</label>
<?php echo form_error('barangay'); //------------------------------------------------?>
</div>
<div class="row">
<div class="input-field col s6">
<select name="city" id="city">
<option value="" disabled selected>Choose a City</option>
<?php
foreach ($cities as $city)
{
echo '<option value="'.$city->city.'">'.$city->city.'</option>';
}
?>
</select>
<label for="city">City</label>
<?php echo form_error('city'); //--------------------------------------------------?>
</div>
</div>
$(document).ready(function(){
/* Populate data to state dropdown */
$('#city').on('change',function(){
var city = $(this).val();
//alert(city);
if(city){
$.ajax({
type:'POST',
url:'index.php/createPatient/getphilippineLocations',
data:'country_id='+city,
success:function(data){
$('#barangay').html('<option value="">Select State</option>');
var dataObj = jQuery.parseJSON(data);
if(dataObj){
$(dataObj).each(function(){
var option = $('<option />');
option.attr('value', this.name).text(this.name);
$('#barangay').append(option);
});
}else{
$('#barangay').html('<option value="">State not available</option>');
}
}
});
}else{
$('#barangay').html('<option value="">Select country first</option>');
}
});
});
//this is the function it is suppose to call
public function getphilippineLocations()
{
$states = array();
$country_id = $this->input->post('country_id');
if($country_id)
{
$states = $this->createPatient_model->getAllBarangays($country_id);
}
echo json_encode($states);
}
function getAllBarangays($city)
{
$sql = "SELECT * FROM ph_locations WHERE city = '".$city."' ORDER BY name ASC";
$query = $this->db->query($sql);
return $query->result();
}
Sadly there is no error message, I can't tell if ajax is running but it suppose to show all the barangays for that city once the city is chosen by the dropdown(an administrative division in the Philippines, similar to village or district)
Hope below will be helpful for you.. try once and let us know if it won't work
<select name="barangay" id="barangay">
<option value="" disabled selected>Choose a Barangay</option>
</select>
var UrlCities = url To Get Cities,
BindDropDownValues(UrlBindBenefitPlans, 'barangay', 'ID', 'Name', true, selectedValueInEditMode);
function BindDropDownValues(url, controlToBind, dataValueField, dataTextField, isSelectRequired, valueToSelect) {
var ajax = $.ajax({
cache: false,
url: url,
dataType: "json",
global: globalAjax,
success: function (data) {
if (data != null && data != undefined && data.length > 0) {
$("#" + controlToBind).empty();
if (isSelectRequired == true) {
$("#" + controlToBind).append($("<option title=\"-Select-\"></option>").val(0).html("--Select--"));
}
for (var itemIndex = 0; itemIndex < data.length; itemIndex++) {
var singleObj = data[itemIndex];
$("#" + controlToBind).append($("<option></option>").val(singleObj[dataValueField]).html(singleObj[dataTextField]));
}
if (valueToSelect != undefined && valueToSelect != "") {
$("#" + controlToBind).val(valueToSelect);
}
}
}
});
return ajax;
};
</script>

How to populate a dropdown with AJAX

I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js

jquery UI.js prevents to load dynamically loaded select menu

I tried to load dynamically loaded select menu for my page using Ajax/PHP. But jquery UI plugging prevents to load that dynamically loaded data. So I can't see nothing when i change the first select menu.
My code like this.
<script>
$(document).ready(function($) {
var list_target_id = 'list-target'; //first select list ID
var list_select_id = 'list-select'; //second select list ID
var initial_target_html = '<option value="">-Select-</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();
//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: 'loadcity.php?svalue='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
</script>
<form method="post">
<div class="select-country">
<label>District</label>
<select name="list-select" id="list-select">
<option value="">Please select..</option>
<?php
$sel_dis2 = mysql_query("SELECT * FROM district", $connection);
confirm_query($sel_dis2);
while($dis2 = mysql_fetch_assoc($sel_dis2)){
?>
<option value="<?php echo $dis2["id_district"]; ?>"><?php echo $dis2["district"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="select-state">
<label>City</label>
<select name="list-target" id="list-target"></select>
</div>
</form>
I tested the code without including jquery UI and it worked properly. But i want to add jquery UI for this page. This is the php file
<?php
$connection = mysqli_connect("localhost", "user", "password", "database");
$selectvalue = mysqli_real_escape_string($connection, $_GET['svalue']);
mysqli_select_db($connection, "database");
$result = mysqli_query($connection, "SELECT city.id_city, city.city FROM city WHERE city.district_id = '$selectvalue'");
echo '<option value="">-Select-</option>';
while($row = mysqli_fetch_array($result))
{
echo '<option value="'.$row['id_city'].'">' . $row['city'] . "</option>";
//echo $row['drink_type'] ."<br/>";
}
mysqli_free_result($result);
mysqli_close($connection);
?>
Something else is breaking your select. Tested at jsfiddle: https://jsfiddle.net/ddpdhr5a/
$(document).ready(function($) {
var list_target_id = 'list-target'; //first select list ID
var list_select_id = 'list-select'; //second select list ID
var initial_target_html = '<option value="">-Select-</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();
//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: 'loadcity.php?svalue='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<form method="post">
<div class="select-country">
<label>District</label>
<select name="list-select" id="list-select">
<option value="">Please select..</option>
<option value="something">Something</option>
</select>
</div>
<div class="select-state">
<label>City</label>
<select name="list-target" id="list-target"></select>
</div>
</form>
This seems to work perfectly, although I had to remove the PHP, naturally, and just use some mock location

Selecting default value in html dropdown list

I am currently looking to have a drop down list in my form. I have this drop down which selects the default value:
<p>Price Band:<select id='priceBand' style = 'width:150px' value = 'band1'>
<option value="band7">Reduce by 30c</option>
<option value="band6">Reduce by 25c</option>
<option value="band5">Reduce by 20c</option>
<option value="band4">Reduce by 15c</option>
<option value="band3">Reduce by 10c</option>
<option value="band2">Reduce by 5c</option>
<option value="band1" selected="selected">default</option>
</select></p>
Which works fine and selects the default as the default value. But what I also need to be able to do - after the form is submitted I want it to keep the last selected value as the default one. It is a form used to add sales with different price bands. The sales are entered by the price bands so the defaults are entered first, the band2, band3 and so on.. What is the best way of doing it? I am currently using javascript and php on the page if that makes it any easier?
Ajax code. I didn't include getting the value of the dropdown as this is only a new thing that I am implementing. I just want to know if it is possible to have a default value selected when the form is loaded first and then when a different value is selected, to keep that value as the new default:
$('#divItemisedSaleAdd').dialog({'autoOpen': false, 'modal' : true, 'buttons' :
[ { text: "Ok", click: function() {
var url = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_sales.php', array('stocktake_id' => $stocktake_id, 'action' => 'add_itemised_sale'));?>';
var productCode = $('#ProductCode').val();
var qty = $('#Quantity').val();
var dialog = this;
$.ajax({
url: url,
dataType: 'json',
data: {'productCode' : productCode, 'qty' : qty},
type: 'post',
timeout: 5000,
success: function(json) {
if (json.status == 'S'){
alert('Sale added');
}
else if (json.status == 'E')
alert('No product with given PLU was found! Please check!');
// loadDepartments();
$( dialog ).dialog( "close" );
},
error: function() {}
});
} } ] });
You can use localStorage for that purpose:
$('#divItemisedSaleAdd').dialog({'autoOpen': false, 'modal' : true, 'buttons' :
[ { text: "Ok", click: function() {
var url = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_sales.php', array('stocktake_id' => $stocktake_id, 'action' => 'add_itemised_sale'));?>';
var productCode = $('#ProductCode').val(),
qty = $('#Quantity').val(),
dialog = this;
// save current selected value in storage
localStorage.setItem("default_option", productCode);
$.ajax({
url: url,
dataType: 'json',
data: {'productCode' : productCode, 'qty' : qty},
type: 'post',
timeout: 5000,
success: function(json) {
if (json.status == 'S'){
alert('Sale added');
}
else if (json.status == 'E')
alert('No product with given PLU was found! Please check!');
// loadDepartments();
$( dialog ).dialog( "close" );
},
error: function() {}
});
} } ] });
// after page reload
if (localStorage.getItem("default_option")) {
$('#ProductCode').val(localStorage.getItem("default_option"));
}
This might do it - either selected = "selected" or just selected depending on whether you will use XHTML or not. It requires making the value a simple integer, but that simplifies cleaning it up by allowing you just to use its intval() which you would use in your query as well as to control the selected option. This version assumed page submission which apparently is not the case here now as it is all done by Ajax but hope it will be useful to someone.
if(!isset($priceBand_value)) $priceBand_value = array();
$priceBand_value = ''; // reset it if already used
// set default 'selected = "selected"'; or just 'selected';
<?php if(!isset($_POST['priceBand']) $priceBand_value[1] = 'selected = "selected"'; ?>
<?php $priceBand_value[intval($_POST['priceBand'])] = 'selected = "selected"'; ?>
<p>Price Band:<select id='priceBand' style = 'width:150px'>
<option value="7" <?php echo $priceBand_value[7] ?>>Reduce by 30c</option>
<option value="6" <?php echo $priceBand_value[6] ?>>Reduce by 25c</option>
<option value="5" <?php echo $priceBand_value[5] ?>>Reduce by 20c</option>
<option value="4" <?php echo $priceBand_value[4] ?>>Reduce by 15c</option>
<option value="3" <?php echo $priceBand_value[3] ?>>Reduce by 10c</option>
<option value="2" <?php echo $priceBand_value[2] ?>>Reduce by 5c</option>
<option value="1" <?php echo $priceBand_value[1] ?>>default</option>
</select></p>
You could start from 0 rather than 1 for most cases but this was intended primarily to fit the code framework given. This would avoid the need to set the default as intval($_POST['priceBand']) would be 0 when the page is first rendered but in this case it could be harder to keep track of the "bands".

Create subcategory select box onChange

I am creating a category system where users can select category from DB and after they select it creates another select box with subcategory of that category.
So, my question is how can I do it the best way?
BTW I am using Laravel Framework and first category is simple
<select>
#foreach(Category::all() as $k)
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
#endforeach
</select>
But what should I do after they pick a category? Is it better to do the AJAX call to send the ID of picked category and returns the subcategory or what?
I need the best and professional way to do this.
In my Database I have
ID, name, parent
Use ajax, after selecting the category send the ajax request and to do this you need to use change event on your select, for example:
// Assumed category is id of the select
$('#category').on('change', function(){
var id = $(this).val();
$.getJSON("subcategory/" + id , function(data){
// Assumed subcategory is id of another select
var subcat = $('#subcategory').empty();
$.each(data, function(k, v){
var option = $('<option/>', {id:k, value});
subcat.append(option);
});
});
});
On the server side, create a route like this (You may use a controller and Eloquent):
Route('subcategory/{id}', function($id){
// Get the data from database according to the id
// Build an array as: id => value and then return
return Response::json($subcat);
});
Populate a dropdown on selecting an option from another dropdown Laravel
This might surely help you. Otherwise ask if you do not understand
select_cat.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".category").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "select_subcat.php",
data: dataString,
cache: false,
success: function(html)
{
$(".subcat").html(html);
}
});
});
});
</script>
Category :
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
include('databasefile');
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
$sql=mysql_query("select cat_name from category order by cat_name");
while($row=mysql_fetch_array($sql))
{
$cname=$row['cat_name'];
echo '<option value="'.$cname.'">'.$cname.'</option>';
} ?>
</select> <br/><br/>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>
2.select_subcat.php
<?php
include('databasefile);
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select s_name from subcat_l1 where cat_name='$id'");
while($row=mysql_fetch_array($sql))
{
$sname=$row['s_name'];
echo '<option value="'.$sname.'">'.$sname.'</option>';
}
}
?>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>

Categories

Resources