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).
Related
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>
I have dropdowns that are being appended dynamically on a page. However, I could not assign the value to the select2. Anyone can help me with this?
Below is what I have try to do to assign the data to select2, but still cannot. Where am I missing??
1. $('select.row-item').eq(index).val(item.itemID);
2. $('.row-item:eq("' + index + '")').val('"' + item.itemID + '"')
3. var $row = $(html)
a. $row.find("row.item option[value=" + item.itemID + "]").prop("selected", true);
b. $row.find('select .row-item').val(item.itemID).trigger('change');
$(function() {
var data = data1
var html = '';
html += '<thead><tr>';
html += '<th>Item</th>';
html += '<th>Description</th>';
html += '<th>Qty</th>';
html += '<th>Total</th>';
html += '</tr></thead>';
html += '<tbody class="acc_table">';
data.forEach((item, index) => {
html += '<tr class="acc-row">';
html += '<td><select class="row-item"><option label="Choose One"> </option><option value="10">ITEM 1</option><option value="20">ITEM 2</option></select></td>';
html += '<td><input class="row-desc" type="text" value="' + item.itemName + '"></td>';
html += '<td><input class="row-qty" type="text" onkeyup="onlyDecimal(this)" value="' + item.itemQty + '"></td>';
html += '<td><input class="row-totalamount" type="text" value="' + item.totalAmount + '" disabled></td>';
html += '</tr>';
//at here I assign the data to select2
$('select.row-item').eq(index).val(item.itemID);
});
html += '</tbody>';
$('.item tbody').empty();
$('.item').append(html);
$('.row-item:last').select2();
$('.item').DataTable({
"paging": false,
"ordering": false,
"info": false,
"searching": false,
});
})
const data1 = [{
"itemID": "10",
"itemName": "Item 1",
"itemQty": "1",
"totalAmount": "50.00"
},
{
"itemID": "20",
"itemName": "Item 2",
"itemQty": "5",
"totalAmount": "150.00"
}
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>
<table class="item">
On closer look, your line:
var $row = $(html);
$row is not used later on, so $row...whatever has no effect. You keep building the html and later do $('.item').append(html);.
So changing the select value within $row has no effect because $row is not appended, only the unchanged html variable.
As you're building HTML, you can add selected directly to the html:
html += '<option value="10"' + (item.itemID == 10 ? "selected" : "") + '>ITEM 1</option>'
html += '<option value="20"' + (item.itemID == 20 ? "selected" : "") + '>ITEM 2</option>'
Alternatively, if the html build can't be changed (or prefer not to, to keep it cleaner), add the itemID has a data-value and then use code later
html += '<select class="row-item" data-itemid="' + item.itemID + '">'
and then use jquery to set the .val(value) based on .data(itemid"):
$('.item').append(html);
$('select.row-item').each(function() {
$(this).val($(this).data("itemid"));
$(this).select2();
});
Note: you only need .trigger("change") after you've converted the select to a select2 - if it's not a select2 yet, then no need to call .trigger("change") (unless, of course, you have some other code that relies on this change and needs to run during initialisation, but would be better to explicitly call that rather than raise an event).
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
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.
I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};