I'm using Jquery and Ajax function to get data from MySql and put it in a div where can I select them.
It works like this:
When I select a country from the list Jquery runs a function to display a list of cities in selected country using getJson. That list is displayed in "inputString" div.
Now I want to show the same data in a html select form, not in a DIV as it is right now.
The HTML looks like:
<select name="country" id="country" class="country">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="serbia">Serbia</option>
</select>
<input size="30" id="inputString" type="text" name="inputString" class="inp"/>
<div class="suggestionList" id="autoSuggestionsList"></div>
Jquery:
$(document).ready(function () {
$("#inputString").keyup(function () { // inputString is DIV where list of cities are listed
var up_country = $("#country option:selected").val();
$.getJSON("cities.php?queryString=" + up_country + "", function (data) {
if (data.length > 0) {
$.each(data, function (i, data) {
var city = data.city;
if (i < 19) {
$('#autoSuggestionsList').append('<li class="k' + i + '">' + city + '</li>');
}
});
}
});
});
});
How can I display the list of cities of the selected country in html select form like this one below if the select country was UK?
<select name="city" id="city" class="city">
<option value='London'>London</option>
<option value='Manchester'>Manchester</option>
<option value='Salford'>Salford</option>
</select>
$('#country').after('<select name="city" id="city" class="city"/>');
$.each(data, function(index, datum){
$('#city').append($('<option/>').val(datum).text(datum));
});
try something like that-
in your html:
<select name="city" id="city" ></select>
and your jQuery code:
$.each(data, function(i, data){
var city = data.city;
if(i < 19){
$('#city').append('<option>'+ city+ '</option>');
}
}
<select class="suggestionList" id="autoSuggestionsList"></select>
<script>
$.getJSON("cities.php?queryString=" + up_country +"", function(data) {
var content = '';
$.each(data, function(){
content += '<option value="' + this.city + '">' + this.city + '</option>';
});
$('#autoSuggestionsList').html(content);
});
</script>
The response from php can be a form or any other html content. You can load html from php if you don't necessarily need to populate the list with jquery
--for example--
response from php
echo '<form>
<select>
<option>London</option>
<option>Manchester</option>
<option>Salford</option>
</select>
</form>
';
ajax loaded content
$('#citiesList').html(data);
Related
I am currently using a JQuery code and a JSON file to load cities in a select> according to the chosen state/province. The JQuery is below.
$(document).ready(function() {
$.getJSON('../../../js/statesCities.json', function(data) {
var items = [];
var options = '<option value="">Selecione</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
});
$("#estados").html(options);
$("#estados").change(function() {
var options_cidades = '<option value="">Selecione</option>';
var str = "";
$("#estados option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.sigla == str) {
$.each(val.cidades, function(key_city, val_city) {
options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#cidades").html(options_cidades);
}).change();
});
});});
The JSON code I am using: https://gist.github.com/letanure/3012978
And the HTML selects:
<div>
<b>Estado:</b>
<select id="estados" class="form-control" name="estadoCliente" required>
<option value="">Selecione</option>
</select>
</div>
<div>
<b>Cidade:</b>
<select id="cidades" class="form-control" name="cidadeCliente" required>
<option value="">Selecione</option>
</select>
</div>
In fact, this code works just fine. But when I want to fill a form using PHP data, the code doesn't help. (The registration page is the same as editing. On the edition page, PHP loads user's information). If all the states and cities were pre-loaded in the HTML (Have all options typed), in order to check which state and city are in the database, I would use an inline PHP's if, considering the variable $state as the state of any user who filled in this form.
<option <?php echo $state=='AB'?'selected': ''?>>AB</option>
But It can't be used because the function $.each won't accept the variables from PHP. So, my question is how can I do this verification to each option, having the state and city saved in a database? I will use this code to load the data of a user, so I can edit information more easily.
PS: I don't know how I could better describe this question on the title.
Because you're loading the data on the frontend you will need to store the backend values somewhere, then once the data has loaded, use the JS to compare and select the correct option.
In your html you could do (supposing you're not using a templating engine):
<div>
<b>Estado:</b>
<select id="estados" class="form-control" name="estadoCliente" initial-val="<?php $estado; ?>" required>
<option value="">Selecione</option>
</select>
</div>
<div>
<b>Cidade:</b>
<select id="cidades" class="form-control" name="cidadeCliente" initial-val="<?php $cidade; ?>" required>
<option value="">Selecione</option>
</select>
</div>
Above you should see the use of initial-val="...", you can call this whatever you want. You will use these values when the data loads...
So, your JS would now use those, like so:
$(document).ready(function() {
$.getJSON('../../../js/statesCities.json', function(data) {
var items = [];
var options = '<option value="">Selecione</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
});
// always cache your jquery dom lookups in a var if queries more than once.
var $estados = $("#estados");
var $cidades = $("#cidades");
$estados.html(options);
$estados.change(function() {
var options_cidades = '<option value="">Selecione</option>';
var str = "";
$("option:selected", $estados).each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.sigla == str) {
$.each(val.cidades, function(key_city, val_city) {
options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$cidades.html(options_cidades);
$cidades.val($cidades.attr("initial-val"));
}).change();
// now set the value on the "estados" <select> and trigger the change event, so the above code runs to change "cidades"
$estados.val($estados.attr("initial-val")).trigger( "change" );
});
});});
That, I hope gets you a solution you can build upon.
I use an AJAX to display my categories. My problem is when I select a category, the dropdown come back always at this initial position
For example, if I click "Panneaux lumineux", the dropdown go back to "Select your categorie" automatically. in this case "Panneaux lumineux" is not selected.
Tk
<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</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 name="current_category_id" value="20" type="hidden" />
</div>
</div>
The issue you have occurs, because your dropdown list is replaced with a new one when you click on the dropdown. Even if the dropdown is visually the same, it isn't in the DOM.
To solve it, you need to save the selected category ID and select it after the dropdown has been replaced.
<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
var selectedCategory = $('select#category_id').val();
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '"' + (category_id == selectedCategory ? ' selected' : '') + '>' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</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 name="current_category_id" value="20" type="hidden">
</div>
</div>
Above the
$.ajax function call
add
var selectedOptionVal = $('#category_id').val();
to save the value you selected.
then use that value to make the correct option selected when you recreate the html. So then try changing
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
to
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}
I have a form, having two list boxes and based on the selected field from the first list, I have to fetch data from the database to create second list box.
I am trying to acheive this with post method, but unable to understand why mey second list is not populating with data...
PHP to fetch data for second list box
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
}
HTML to for the list boxes
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="c">CC</option>
<option value="d">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid"> <br />
<option value="">Home_Floor</option>
<?php foreach ($HF_id as $row){echo '<option value="' . $row['floor'] . '">' . $row ['floor'] . '</option>';}?>
</select>
Jquery
$('#PC1').on('click', function() {
$.post('user_info1.php', 'val=' + $(this).val(), function (response) {
$.ajax({
url: 'user_info1.php', //This is the current doc
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
}
});
You seem to expect the post function to trigger a loading of the page specified by the URL parameter.
Try something along the lines of this:
HTML
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="C">CC</option>
<option value="D">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid">
</select>
loaddata.php
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
$HF_array=array();
foreach ($HF_id as $row)
{
$HF_array[]=$row['floor'];
}
}
echo json_encode($HF_array);
javascript/jquery
jQuery('#PC1').on('click', function() {
jQuery.ajax({
url: 'loaddata.php',
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
//data should come as JSON string in the form of ['item1','item2','item3'] use JSON.parse to convert to object:
jQuery.each(JSON.parse(data), function(key, datavalue) {
jQuery('#hfid').append(
jQuery('<option>', { value : datavalue })
.text(datavalue)
);//end of append
});//end of each
}//end of success function
});//end of ajax datastruct and ajax call
});//end of on-click-function
Need help for setting up a default select option form my conditional dropdown select.
Here is my first dropdown select
<select name="category" id="category">
<option value="" disabled selected>Select category</option>
#foreach($categories as $cats)
<option value="{{$cats->id}}">{{$cats->name}}</option>
#endforeach
</select>
My dependent dropdown is like this
<select name="product" id="product">
<option value=""></option>
</select>
JS
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
$.get('/products?cat_id=' + cat_id, function(data){
$('#product').empty();
$.each(data, function(index, subcatObj){
$('#product').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
});
});
});
</script>
For a simple dropdown select, like the categories one, simply used the and it worked fine, but how can I have this default select for the products drowdown select?
Appreciate any help.
You can append something like this
$('#product').empty();
$('#product').append('<option value="" disabled selected>Select Product</option>');
});
$.each(data, function(index, subcatObj){
$('#product').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
});
i have seen you have used $('#product').empty(); and hence your included <option value=""></option> is getting removed altogether which you put in your html.
You can use .html() instead of .append() so you do not need to $('#product').empty(); as .html() will overwrite your dom.
And then you can only need to put this in your html
<select name="product" id="product">
</select>
And your javascript will be something like this
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
var response = '';
$.get('/products?cat_id=' + cat_id, function(data){
response = '<option value="" disabled selected>Select Product</option>';
$.each(data, function(index, subcatObj){
response .= '<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>';
});
$('#product').html(response);
});
});
</script>
you can find difference between .html() and .append() here What is the difference between .empty().append() and .html()?
I want to create two select boxes: One that gets it's options from a database and the other that gets it's options depending on the value of the first select box.
My current code is below (I got the value from the first box with an alert, but don't know how to get it in the sql query for the second box). My document name is tutorial.php and I'm not using any other files except for the database functions, which are in include/config.php.
I've followed dozens of tutorials and stack overflow answers, but I can't get it to work. How can I get the select values to the php code on the same page?
jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="js/script.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( "#shoot" ).change(function(){
id_firstSelect = $("#shoot").val();
loadSecondSelect(id_firstSelect);
});
function loadSecondSelect(first_id)
{
$("#model").ready(function(e)
{
$.get(
route.php, //Filter your select
params, // In this case your id
function(result)
{
$("#model").empty();
$("#model").append('<option value="0">-- Select --</option>');
if(result.response['id_second'].length) // this receive your data
{
for(var i=0, len=result.response['id_2'].length; i<len; i++)
{
$("#model").append('<option value="' + result.response['id_2'][i] + '">' + result.response['name_2'][i]+'</option>');
}
}
},
"json");
});
}
});
</script>
form with php functions:
<form action="" method="POST" enctype="multipart/form-data">
<div>
<select name="category">
<option value="paard" selected>Paarden</option>
<option value="hond">Honden</option>
<option value="mens">Mensen</option>
<option value="eigen">Eigen werk</option>
</select>
<input type="file" name="files[]" multiple id="file"/><p>
Ophalen uit database shoots:
<select name="shoot" id="shoot">
<?php
$values = mysql_query("SELECT distinct name FROM shoots") or die(mysql_error());
//$numrows = mysql_num_rows($values);
while ($result=mysql_fetch_array($values)){
echo "<option value='".$result['name']."'>".$result['name']."</option>";
}
?>
</select><p>
<select name="model" id="model"></select>
<label class="radio">Portfoliomateriaal</label>
<input type="radio" name="folio" value="TRUE" /> <span>Ja</span>
<input type="radio" name="folio" value="FALSE" checked /> <span>Nee</span><p>
<input type="submit" value="Upload" id="submit" />
</div>
</form>
In the first select, you could call a function with the id of the select to filtrate the data of the second select like:
in the first select you could do this to fill the second with the first id:
$( "#id_firstSelect" ).change(function()
{
id_firstSelect = $("#id_firstSelect").val();
loadSecondSelect(id_firstSelect);
}
and call the function to load the second select
function loadSecondSelect(first_id)
{
$("#id_secondSelect").ready(function(e)
{
$.get(
route.php, //Filter your select
params, // In this case your id
function(result)
{
$("#id_secondSelect").empty();
$("#id_secondSelect").append('<option value="0">-- Select --</option>');
if(result.response['id_second'].length) // this receive your data
{
for(var i=0, len=result.response['id_2'].length; i<len; i++)
{
$("#id_secondSelect").append('<option value="' + result.response['id_2'][i] + '">' + result.response['name_2'][i]+'</option>');
}
}
},
"json");
});
}