I am trying to create a dynamic set of dropdown boxes, using jQuery/AJAX and PHP/MySQL. The first dropdown box will be populated when the page loads based on values from a database. The second dropdown box should display a set of values based on the selection from the first dropdown box.
I used Chosen plugin in order to have search option.
My problem is: when I select the first selectbox, nothing is shown in the second selectbox. when I remove class="chosen-select"from the Html, it works correctly!
I need the search in selectbox. So, what should I do?
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('.chosen-select').chosen({
no_results_text: "Oops, nothing found!"
});
$('#search1').on('change', function (){
$('#search2').html("<option value=''>Select</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {id: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['Date'] + '</option>';
}
$('#search2').html(options);
//$('.chosen-select').chosen();
});
});
});
</script>
This is the second select:
<select id="search2" name="search" type="text" data-placeholder="Choose an Option..." style="width:370px;" class="chosen-select" onChange="drawChart(this.value);">
<option value=""></option>
</select>
Thank you in Advance.
Finally, I found the answer :)
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('.chosen-select').chosen({
no_results_text: "Oops, nothing found!"
});
$('select#search1').on('change', function (){
$('select#search2').html("<option value=''>Select the Option..</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {id: $(this).val()}, function(data){
$('select#search2').empty();
var options = '<option value="0">Select the Option..</option>';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['Date'] + '</option>';
}
$('select#search2').chosen();
$('select#search2').html(options);
$("#search2").trigger("chosen:updated");
});
});
});
</script>
Related
i am trying to build an crud operation with php and js(ajax) and i have some filters which user can add more filters to a category works fine on adding operation, but on edit i did with ajax and on click is retriving from databse and fill the inputs but on select2 i retrive data like this:
var main_id = $(this).attr("id");
$.ajax({
url:"<?php echo $site_url;?>/actions/get_filters.php",
method:"POST",
data:{main_id:main_id},
dataType:"json",
success:function(data){
var fl = [];
var nr = [];
$.each(data, function(i, field){
fl.push(field.fil_opt+","+field.txt_fil);
nr.push(field.id);
});
for (i = 0; i < nr.length; ++i) {
$('#filters_cat_update > option').each(function() {
$(this).attr('data-id', nr[i++]);
});
}
$('#filters_cat_update').val(fl);
$('#filters_cat_update').trigger('change'); // Notify any JS components that the value changed
}
});
I detect when i remove an option like this:
//remove from edit options
$('#filters_cat_update').on('select2:unselecting', function (e) {
console.log(e.params.args.data.id);
});
My html looks like this:
<div class="col-lg-6 col-md-12 col-sm-12">
<select class="js-example-basic-multiple custom-select mr-sm-2" name="filters_update[]" multiple="multiple" id="filters_cat_update">
<?php
$sqlf = mysqli_query($conn, "SELECT * FROM filtre WHERE vizibil=1 ORDER BY pozitie");
while ($rf = mysqli_fetch_assoc($sqlf)) {?>
<option data-id="" value="<?=$rf['id'];?>,<?=$rf['nume'];?>"><?=$rf['nume'];?></option>
<?php } ?>
</select>
</div>
What i want to do is when i click one option for example "color" to go with ajax and delete from table mysql where i have filters saved for each category and remove it.
As you see in my option i have concatenaded id of filter and name of filter coming from another table where user can create filters.
Thank you in advance.
You can get data-id using $("#filters_cat_update option:selected") which will give you selected option using this you can use .attr and .val() to get required values .
Demo Code :
$('#filters_cat_update').select2();
$('#filters_cat_update').on('select2:unselecting', function(e) {
var code = $("#filters_cat_update option:selected").attr('data-id'); //getting id
var values = $("#filters_cat_update option:selected").val(); //get values
var datas = values.split(',');
var id = datas[0]; //id
var color = datas[1]; //color
console.log("id - " + id + " color - " + color + " data-id -" + code)
//ajax call
$.ajax({
url: "your url",
method: "POST",
data: {
id: id,
color: color,
code :code
}, //send data
success: function(data) {
console.log("done")
}
});
});
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select class="js-example-basic-multiple custom-select mr-sm-2" name="filters_update[]" multiple="multiple" id="filters_cat_update">
<option data-id="2" value="1,Color">Color</option>
<option data-id="7" value="2,Color2">Color2</option>
<option data-id="77" value="3,Color3">Color3</option>
</select>
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 have a multi select drop down. I need a div to be filled with pages based on the selections. I have this working for one selection at a time. I need it to also work when I select more than one option the corresponding pages will populate the div.
For exemple... if I select Item1 and Item2. I want the pages item1.php and item2.php displayed in my div. If I then delete item1 from the selection (using chosen.js) I need only item2.php to show since that is the only current selection.
Here is my current code:
$('#maindiv').on('change', function(event) {
var selected = $(this).val();
$.ajax({
url: 'includes/'+ selected + '.php',
type: 'POST',
data: { cat: selected },
})
.done(function(data) {
$('#displaydiv').html(data)
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
jsfiddle Link. You can't get any output from here but you have to use this in your server.
For more clarification about the page is get or not, see this jsfiddle link. Here you can see the page which will load.
jQuery:
$(function(){
$('#maindiv').on('change', function(event) {
$('#displaydiv').html("");
selected = $(this).val() + "";
arr = selected.split(",");
i = 0;
$(arr).each(function(){
$.get('includes/'+ arr[i] + '.php', function( data ) {
$('#displaydiv').append(data);
});
i++;
});
});
});
HTML:
<select multiple id="maindiv">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<div id="displaydiv">
</div>
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);
i have two select box, now what i want is
i want to move option from one select box to another via a button
below is my code:
php
<table>
<tr>
<td>
<select size="5" id="suppliedMovies" name="suppliedMovies">
<option selected="selected" value="">Select Movie</option>
<option value="1">sholay</option>
<option value="3">Jism</option>
<option value="4">Rog</option>
<option value="5">Zeher</option>
<option value="6">Awarpan</option>
<option value="7">Paap</option>
<option value="8">paanch<option>
<option value="9">no entry</option>
</select>
</td>
<td>
<input type="button" id="toRight" value=">>"><br>
<input type="button" id="toLeft" value="<<">
</td>
<td>
<select size="5" id="accquiredMovies" name="accquiredMovies">
<option> No item right now</option>
</select>
</td>
</tr>
</table>
Jquery
jQuery(document).ready( function() {
function displayVals() {
var myValues = jQuery("#suppliedMovies").val();
return myValues;
}
jQuery('#toRight').click(function(){
var x=displayVals();
console.log(x);
var txt=jQuery("#suppliedMovies option[value='"+x+"']").text();
console.log(txt);
if(x!=''){
jQuery('#accquiredMovies').append("<option value='"+x+"' >"+txt+"</option>");
}
});
});
i m using above jQuery, that is working fine but, i want that
when one item is copy from one select box to another select box, then that item should be disable(or probably delete) from first select box (to prevent duplicate entry).
i also want to move item from right to left select box
please suggest me optimized jQuery .
Thanks.
UPDATE
if i want to use multiple select box on both side? then how do i use that?
more update
if i click on a item on rightselectbox and move it to left selectbox,
and go further(post) then on right selectbox, there is nothing selected items??
what i need is on right selectbox, there all items shoud be always selected ,
otherwise what i need to do? after i move an item from right to left ,i again have to select rest of items on right selectbox and go further
solution for my update part
i used below code, please take a look and suggest me if somebody finds any mistake/error in this. Thanking You
jQuery('form').submit(function() {
jQuery('#accquiredMovies option').each(function(i) {
jQuery(this).attr("selected", "selected");
});
});
You could use jQuery remove. Like:
$('#suppliedMovies option[value=' + x ']').remove()
..fredrik
EDIT:
You could optimize the function like this:
jQuery(document).ready( function() {
# Store the jQuery object return by the selector so that you don't need to
# make a new selector request next time a user press the #toRight
var suppliedSelect = jQuery('#suppliedMovies');
jQuery('#toRight').click(function () {
suppliedSelect.find(':selected').each(function (index, elem) {
var selectElem = $(elem);
if (selectElem.val()) {
selectElem.val.appendTo('#accquiredMovies');
}
});
});
});
function SelectMoveRows(SS1,SS2)
{
var SelID='';
var SelText='';
// Move rows from SS1 to SS2 from bottom to top
for (var i=SS1.children().length - 1; i>=0; i--)
{
if (SS1.children()[i].selected == true)
{
SelID=SS1.children()[i].value;
SelText=SS1.children()[i].text;
SS2.append($("<option/>", {value: SelID, text: SelText}));
$(SS1.children()[i]).remove();
}
}
SelectSort(SS2);
}
function SelectSort(SelList)
{
// alert("in secod "+(SelList.children().length-1))
var ID='';
var Text='';
for (var x=0; x < SelList.children().length-1; x++)
{
// alert(SelList.children()[x].text)
for (var y=x + 1; y < SelList.children().length; y++)
{
if ($(SelList.children()[x]).val() > $(SelList.children()[y]).val())
{
// Swap rows
alert("x "+SelList.children()[x].value +" y = "+SelList.children()[y].value)
ID=$(SelList.children()[x]).val();
Text=$(SelList.children()[x]).text();
$(SelList.children()[x]).val($(SelList.children()[y]).val());
$(SelList.children()[x]).text($(SelList.children()[y]).text());
$(SelList.children()[y]).val(ID);
$(SelList.children()[y]).text(Text);
// SelList.children()[x].text= SelList.children()[y].text;
// SelList.children()[y].value=ID;
// SelList.children()[y].text=Text;
}
}
}
}
This is also working for moving items from one multi select box to another without duplicating. I wana know how to make order of values same while moving items from one to another select box.
Here's a good example:
HTML:
<form>
<select id="t1available" size=10 multiple><option>Project 1</option><option>Project 2</option><option>Project 4</option></select>
<br />
<input id="t1add" type="button" value=">" />
<input id="t1addAll" type="button" value=">>" />
<input id="t1removeAll" type="button" value="<<" />
<input id="t1remove" type="button" value="<" />
<br />
<select id="t1published" size=10 multiple><option>Project 3</option></select>
</form>
Jquery:
<script type="text/javascript">
function moveSelectedItems(source, destination){
var selected = $(source+' option:selected').remove();
var sorted = $.makeArray($(destination+' option').add(selected)).sort(function(a,b){
return $(a).text() > $(b).text() ? 1:-1;
});
$(destination).empty().append(sorted);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#t1add').click(function(){
moveSelectedItems('#t1available', '#t1published');
});
$('#t1addAll').click(function(){
$('#t1available option').attr('selected', 'true');
moveSelectedItems('#t1available', '#t1published');
});
$('#t1remove').click(function(){
moveSelectedItems('#t1published', '#t1available');
});
$('#t1removeAll').click(function(){
$('#t1published option').attr('selected', 'true');
moveSelectedItems('#t1published', '#t1available');
});
});
</script>
This example is entirely from the following article, which, unfortunately for English speakers, is in German: Move selected items between checkboxes.
We can do like this:
$('div.buttons').on('click','#add',function(e){
e.preventDefault();
$("#sourceid option:selected").appendTo("#destinationid");
});