jquery ui autocomplete comobox recreating options not working - javascript

hi i am using jquery ui autocomplete combobox plugin , i am creating a combobox initially in document.ready
jQuery('#combolist_city').combobox();
i set some options when page is loading
<select id="combolist_city" class="city" name="search[city]">
<option value="0">Select city</option>
<?php
if(isset($city_list))
{
foreach($city_list as $city_data)
{
if(isset($selected_city) && ($selected_city == $city_data['CityID']))
{
echo "<option selected='selecetd' value=".$city_data['CityID'].">".$city_data['CityName']."</option>";
}
else
{
echo "<option value=".$city_data['CityID'].">".$city_data['CityName']."</option>";
}
}
}
?>
</select>
now i want to change his options, i am tying to do it by
jQuery("#combolist_city").combobox({
initialValues: ['aaa','bbb','ccc']
});
but it is not working , it is not recreating the options ,
how can i do this , please help.............................

You have to do it manually. First destroy the combobox and empty the select. Append the new options and build the combobox again:
var aList = {'id1': 'val1', 'id2': 'val2', 'id3': 'val3'};
var sKey;
$("#combolist_city").combobox('destroy').empty();
for (sKey in aList) {
$("#combolist_city").append('<option value="' + sKey + '">' + aList[sKey] + '</option>');
}
$("#combolist_city").combobox();
Also see this example.

Related

How do I populate a select using JSON based on previous selection?

I'm trying to create two select dropdowns for provinces and their cities. The idea is that I first select the province on the first dropdown, and after that, only the cities from that province will show on the second select.
I have this JSON file with the provinces and cities in Catalonia. I edited the file myself so I could have an array of all the cities of each province but I don't know if it's the best way to show the cities in the select though. Here I show you a short version of the JSON file because the original it's too big:
{
"Barcelona":[
[
"Abrera"
],
[
"Aguilar de Segarra"
],
[
"Alella"
]
],
"Girona":[
[
"Agullana"
],
[
"Aiguaviva"
],
[
"Albanyà"
]
],
"Tarragona":[
[
"Aiguamúrcia"
],
[
"Albinyana"
],
[
"Albiol, l'"
]
],
"Lleida":[
[
"Abella de la Conca"
],
[
"Àger"
],
[
"Agramunt"
]
}
I have been able to create the first select and it shows the 4 provinces correctly with this code:
<select name="activity_province" class="form-select" id="activity_province">
<option hidden selected></option>
<script type="text/javascript">
$(document).on('ready',function (){
$.getJSON('/../public/utils/municipios.json', function(data) {
$.each(data, function(key, value) {
$("#activity_province").append('<option name="' + key + '">' + key + '</option>');
});
});
});
</script>
</select>
<label for="activity_province">Province</label>
But when I try to do the second one (cities) I get on each option of the select all the cities from each province together, separated by commas like this:
Cities select
The code of the second select is the following:
<select name="activity_city" class="form-select" id="activity_city">
<option hidden selected></option>
<script type="text/javascript">
$(document).on('ready',function (){
$.getJSON('/../public/utils/municipios.json', function(data) {
$.each(data, function(key, value) {
$("#activity_city").append('<option name="' + value + '">' + value + '</option>');
});
});
});
</script>
</select>
<label for="activity_city">City</label>
I would like to know how to iterate correctly all the cities when I have selected a province. And if you think the JSON file should be organised in a different way for easier access please let me know.
Thank you very much in advance.
I've modified your code a bit, for testing purposes. The relevant fiddle can be found here.
The adjustments I've made refer to omitting the call to an external JSON - I've made a variable out of it, for testing and illustrative purposes. Also, if your regions and cities list is more or less constant, you can just include it as an external JS file. For example:
<script src="/public/utils/municipios.js></script>
And the contents of that JS file would be a JSON variable (minified or not, depending on the number of regions and cities within those regions).
The key point here is that your #activity_province is populated from the keys of your JSON file (or JSON variable, if you organize everything as I've suggested). You can do that right away, on $(document).ready(...).
The contents of #activity_city appear once a region has been selected. Since the cities are the values associated with the specific region key, you would need to extract them from your JSON, clear the previous contents of #activity_city, and then repopulate it with whatever was listed for the selected region.
var regions = {
"Barcelona": [
"Abrera",
"Aguilar de Segarra",
"Alella"
],
"Girona": [
"Agullana",
"Aiguaviva",
"Albanyà"
],
"Tarragona": [
"Aiguamúrcia",
"Albinyana",
"Albiol, l'"
],
"Lleida": [
"Abella de la Conca",
"Àger",
"Agramunt"
]
};
$(document).ready(function (){
var province = Object.keys(regions);
var options = "";
for(var i = 0; i < province.length; i++) {
options += '<option value="' + province[i] + '">' + province[i] + '</option>';
}
$("#activity_province").append(options);
$("#activity_province").on("change",function() {
var chosenProvince = $(this).val();
var basicOption = '<option value="">Please choose a city</option>';
var cityOptions = "";
var cities = regions[chosenProvince];
if(cities) {
for(var i = 0; i < cities.length; i++) {
cityOptions += '<option value="' + cities[i] + '">' + cities[i] + '</option>';
}
}
$("#activity_city").html(basicOption + cityOptions);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="activity_province">Province</label>
<select name="activity_province" class="form-select" id="activity_province">
<option value="" selected>Please choose a province</option>
</select>
<label for="activity_city">City</label>
<select name="activity_city" class="form-select" id="activity_city">
<option value="" selected>Please choose a city</option>
</select>

Trouble trying to use JSON and JS with jQuery

I'm trying to get the field 'sigla' from a JSON file and put it on a HTML 'option object', but it's refusing to work as it should.. hope some of you out there can help me with that!
This is a sample of the JSON file:
{
"estados": [
{
"sigla": "AC",
"nome": "Acre",
"cidades": [
"Acrelândia",
"Assis Brasil"
]
},
{
"sigla": "AL",
"nome": "Alagoas",
"cidades": [
"Água Branca",
"Anadia"
]
}, ...
]
}
Script:
<script>
$.getJSON("json/estados.json", function (data){
$.each(data.estados, function (keyEstados, valEstados){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(valEstados.sigla, function (keySigla, valSigla){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
});
</script>
Where it should fit in:
<div class="col-sm-6">
<div class="inputBox">
<div class="inputText">Selecione seu estado*
<select id="selection" name="estado_php" required>
<option value="" disabled="disabled" selected>UF</option>
</select>
</div>
</div>
</div>
It seems to me that you are fetching the valEstados.sigla as it was an object or an array ($.each(valEstados.sigla) and it has the value you need to set the options.
Besides that, you are setting a disabled option and the html of the select one time for each data.estados instead of just once.
This should work:
$.getJSON("json/estados.json", function (data) {
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(data.estados, function (keyEstados, valEstados) {
output += '<option value="' + valEstados.sigla + '">' + valEstados.sigla + '</option>';
});
$('#selection').html(output);
});
Have you tried using the "developer" mode in your browser to set breakpoints in your code to debug it? E.g. on Firefox, the menu has a top level entry to "Web Developer"->"Debugger".
If you do, I think you will find have mixed up your loops. The first loop looks OK in that
$.each(data.estados, function (keyEstados, valEstados){...
should match the list starting
"estados": [...]
However, I don't think the second loop starting
$.each(valEstados.sigla, function (keySigla, valSigla){
is needed. I think your code needs to look more like this:
$.getJSON("json/estados.json", function (data){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(data.estados, function (keyEstados, valEstados){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
(not tested, but it basically gets rid of the inner loop).

How to programmatically select an option inside a variable using jQuery

Let say I have this variable html which contain these select options:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
How can I programmatically select an option which is inside the html variable so when I append them to somewhere, for example
$(this).children('div').append(html);
it will become like this:
<div> <!-- children div of the current scope -->
<select>
<option value="10" selected>10</option>
<option value="20">20</option>
</select>
</div>
How is it possible?
edit: the variable contents is generated from remote locations, and I must change the value locally before it is being appended into a div. Hence, the question.
edit 2: sorry for the confusion, question has been updated with my real situation.
You can cast the HTML into a jQuery element and select the value at index 0. Then you can add it to the DOM.
Here is a simple jQuery plugin to select an option by index.
(function($) {
$.fn.selectOptionByIndex = function(index) {
this.find('option:eq(' + index + ')').prop('selected', true);
return this;
};
$.fn.selectOptionByValue = function(value) {
return this.val(value);
};
$.fn.selectOptionByText = function(text) {
this.find('option').each(function() {
$(this).attr('selected', $(this).text() == text);
});
return this;
};
})(jQuery);
var $html = $([
'<select>',
'<option value="10">10</option>',
'<option value="20">20</option>',
'</select>'
].join(''));
$('#select-handle').append($html.selectOptionByIndex(0));
// or
$html.selectOptionByValue(10);
// or
$html.selectOptionByText('10');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-handle"></div>
By default, the first option will be selected - if you want to do on any other set it so using the index as soon as the select is appended:
$('#select_handle option:eq(1)').prop('selected', true)
(this selects the second option)
See demo below:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
$('#select_handle').append(html);
$('#select_handle option:eq(1)').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select_handle"></div>
You could try simply setting the value of the drop-down to the one you wish to 'select' - like
$("#select_handle select").val( a_value );
For example, if a_value is 30 it will add the needed HTML to the DOM node. This would be my take:
$(function() {
var html = '<select>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select>';
// set a value; must match a 'value' from the select or it will be ignored
var a_value = 30;
// append select HTML
$('#select_handle').append(html);
// set a value; must match a 'value' from the select or it will be ignored
$("#select_handle select").val(a_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>select added below</h2>
<div id="select_handle">
</div>
selected="selected" will work
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20" selected="selected">20</option>'+
'</select>';
$('#select_handle').append(html);
You can do this in jQuery using the .attr() function and nth pseudo-selector.
Like so:
$("option:nth-child(1)").attr("selected", "");
Hope it helps! :-)
after the append, try $('#select_handle select').val("10"); or 20 or whatever value you want to select

create a select dropdown option with values and text according to the specified data attribute

so below is my snippet. What I want is to create a select dropdown option base from the data attribute (data-select-text and data-select-values) of the currently clicked button, so below is a working snippet except for getting the data-select-values which is the problem because i dont know how to loop it along with the data-select-text so that the result of each select option will have values and text base from the split values of the data-select-text and data-select-values attribute, any ideas, help, suggestions, recommendations?
NOTE: currently, I could only able to use the attribute data-select-text as a select options values and text.
$(document).ready(function(){
$(document).on("click", "button", function(){
if($(this).attr("data-input-type").toLowerCase() === "select"){
var classList = $(this).attr('data-select-text').split(/\s+/);
var field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + item.replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
You could create an array for the values, the same as so did for the text.
Make sure that the order in both data-select-text and data-select-values is the same. Then you can use the index in your $.each loop:
$(document).ready(function(){
$(document).on("click", "button", function(){
var elem = $(this);
if( elem.attr("data-input-type").toLowerCase() === "select" ){
var classList = elem.data('select-text').split(/\s+/),
valueList = elem.data('select-values').split(/\s+/),
field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + valueList[index].replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
The result will be:
<select>
<option value="1">select 1</option>
<option value="2">select 2</option>
<option value="3">select 3</option>
</select>
Here is one way to do it, if I understand correctly. This code does not take into account different text or value lengths. It expects that the text length of options created is always equal to the values length being used.
$(document).ready(function () {
$(document).on("click", "button", function () {
if ($(this).attr("data-input-type").toLowerCase() === "select") {
var classList = $(this).attr('data-select-text').split(/\s+/);
var valueList = $(this).attr('data-select-values').split(' ');
var field = '<select>';
$.each(classList, function (index, item) {
field += '<option value="' + valueList[index] + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
Fiddle: http://jsfiddle.net/32qt0vn8/

jQuery: xml: How to change xml code via jQuery and id

I'm trying to change content in an XML by using jQuery.
From the examples that I've been looking up I think the code should be something like this:
javascript:
get_verrichtingen: function(){
var self = this;
var optie = "hello";
self.$( "#verrichting-select" ).html( '<option value="' + optie + '">' + optie + '</option>' );
},
XML:
<div id="cashier-frame">
<t t-esc="widget.get_verrichtingen()">
<select>id="verrichting-select"</select>
</t>
</div>
My goal is to create a dropdown menu later.
I think the reason this doesn't work might have to do something with where I've put the id="verrichting-select".
But I THINK it should be there because <select><option value="Hallo">Hallo</option></select> actually works?
Right now with the jQuery, the dropdown is just empty.
What am I doing wrong here?
edit: FYI: I'm trying to do this in Odoo Point of Sale.
edit for Emipro Technologies Pvt:
I can only see "All" in the dropdown but can't click it to see other values.
I've tried to make a very simple dropdown, but this doesn't work either. I only see "Volvo" with the code below:
<div id="cashier-frame">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
I can't click the arrow.
Could this have something to do with Odoo?
You need to do this in few steps,
First you need to define dropdown in xml,
<select id="sele_filter" name="sele_filter">
<option value="All" selected="true">All</option>
</select>
Then in your widget code you need to build options first and then append it to the dropdown.
var options = "";
var i=0;
options += '<option value="' + i++ + '">' + i + </option>';
options += '<option value="' + i++ + '">' + i + </option>';
options += '<option value="' + i++ + '">' + i + </option>';
this.$el.find('#sele_filter').append(options);
$el will accessible through out Point of Sale.

Categories

Resources