I am working on a project in which i have to append a dropdown options to selection list .I have tried to append options but am not getting them in dropdown. while i am getting values in debugging
$("#p_combination").empty();
for(var i = 0; i < len; i++) {
var dish_name = response[i]['dish_name'];
var pincode = response[i]['pincode'];
$("#p_combination").append("<option value='" + dish_name + "'>" + dish_name + "</option>");
document.getElementById('pincode').value = pincode;
}
<select name="p_combination[]" id="p_combination" multiple>
<option value="0">Select</option>
</select>
Try this:
$("#p_combination").empty();
//supposing that your response object is something like :
var response=[{'dish_name':'name1','pincode':1},{'dish_name':'name2','pincode':2},{'dish_name':'name3','pincode':3}];
for(var i = 0; i < response.length; i++) {
$("#p_combination").append("<option value='" + response[i]['dish_name'] + "'>" +response[i]['dish_name'] + "</option>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<select name="p_combination[]" id="p_combination" multiple>
<option value="0">Select</option>
</select>
You can use the .append() method in jQuery as in the following example.
Working Example:
$(document).ready(function(){
$('button').click(function(){
var newOptionValue = $('option').length;
$('select').append('<option value="' + newOptionValue + '">Option ' + newOptionValue + '</option>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="p_combination[]" id="p_combination" multiple>
<option value="0">Option 0</option>
</select>
<button type="button">Append Option</button>
Related
So the idea is to manipulate the value that is delivered by Ajax. This value should be divided by 20 and the result should be multiplied by the value from #nilai_hari input.
Here's my code
// trigger
<select class="form-control" id="id_anggota" name="id_anggota">
<option>-Pilih Karyawan</option>
<?php $no=1; foreach ($listAnggota as $l) {?>
<option value="<?php echo $l->id_anggota; ?>">
<?php echo $l->nama_lengkap; ?>
</option>
<?php $no++; }?>
</select>
// the effected
<select class="tunjangan_makan form-control total_tunjangan nominal" id="tunjangan_makan" name="tunjangan_makan"></select>
// another trigger
<input type="text" id="nilai_hari" name="nilai_hari" class="form-control">
And here's the script
$('#id_anggota').change(function() {
var id = $(this).val();
$.ajax({
url: "<?php echo base_url();?>hrd/penggajian/get_subpenggajian",
method: "POST",
data: {
id: id
},
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
if (data[i].flat_tunjangan == 1) {
html += '<option value="' + data[i].tunjangan_makan + '">' + number_format(data[i].tunjangan_makan, 0, '', '.') + '</option>';
} else {
$('#tunjangan_makan', '#nilai_hari').keyup(function() {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan / 20) * nilai_hari)
html += '<option value="' + makan + '">' + number_format(makan, 0, '', '.') + '</option>';
})
}
}
$('.tunjangan_makan').html(html);
}
});
});
So, the value of the data in which flat_tunjangan is 0 must be calculated from another input. Thanks in advance
You are doing it wrong. You should call other input onkey event and call same ajax request again and remove that onkey event inside $('#id_anggota').change().
$('#id_anggota').change(function(){
var id=$(this).val();
// perform ajax and get data
var data = [{'flat_tunjangan': '1', 'tunjangan_makan': '20'}, {'flat_tunjangan': '0', 'tunjangan_makan': '30'}];
var html = '';
var i;
for(i=0; i<data.length; i++){
if(data[i].flat_tunjangan == 1){
html += '<option value="'+data[i].tunjangan_makan+'">'+data[i].tunjangan_makan+'</option>';
} else {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan/20)*nilai_hari)
if (makan != '') {
html += '<option value="'+makan+'">'+makan+'</option>';
}
}
}
$('.tunjangan_makan').html(html);
});
$("#nilai_hari").keyup(function(){
var nilai_hari = $(this).val();
// again do ajax reqeust and fetch data using selected tunjangan_makan id
var id = $('#id_anggota').val();
var data = [{'flat_tunjangan': '1', 'tunjangan_makan': '20'}, {'flat_tunjangan': '0', 'tunjangan_makan': '30'}];
var html = '';
var i;
for(i=0; i<data.length; i++){
if(data[i].flat_tunjangan == 1){
html += '<option value="'+data[i].tunjangan_makan+'">'+data[i].tunjangan_makan+'</option>';
} else {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan/20)*nilai_hari)
if (makan != '') {
html += '<option value="'+makan+'">'+makan+'</option>';
}
}
}
$('.tunjangan_makan').html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="id_anggota" name="id_anggota">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
</select>
<select class="tunjangan_makan form-control total_tunjangan nominal" id="tunjangan_makan" name="tunjangan_makan"></select>
<input type="text" id="nilai_hari" name="nilai_hari" class="form-control">
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 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>
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);