Dynamic option groups for Select element based on alphabet - javascript

I'm generating a select list dynamically from an array of data and I want to add option group based on alphabet.
e.g. data
data = [
['bcde','21254'], ['abcd','1234'], ['abcde','23456'], ['bcdef','3232']
];
data.sort(); takes care of ordering based on alphabet and then I go through the data and on each I do something like:
<option value="item[1]">item[0]</option>
However what I want to do is, after getting the items sorted based on alphabet, check the first character of each item and create option group based on that, when character of next item is different create a new option group labelled with the new character
so the output should look like:
<select>
<optgroup label="A">
<option value="1234">abcd</option>
<option value="23456">abcde</option>
</optgroup>
<optgroup label="B">
<option value="21254">bcde</option>
<option value="3232">bcdef</option>
</optgroup>
</select>
Can anyone please advice what's the best way to do this, I'm using jquery by the way, cheers.
Edit, this is my current code:
$.when( $.indexedDB("dbname").objectStore('employee').each(function(item){
employeenames.push([item.value.name,item.value.id]);
}).then(function(){
employeenames.sort();
$.each(employeenames, function(index, item){
employeenames[index] = '<option value="'+item[1]+'">'+item[0]+'</option>';
});
})
).done(function() {
$("#employeenameBox select").html(employeenames);
});

Try
data.sort();
var chars = {};
$.each(data, function (_, item) {
var char = item[0].charAt(0).toUpperCase();
if (!chars[char]) {
chars[char] = $('<optgroup />', {
label: char
}).appendTo('select');
}
$('<option />', {
text: item[0],
value: item[0]
}).appendTo(chars[char]);
});
Demo: Fiddle
Update:
$.when($.indexedDB("dbname").objectStore('employee').each(function (item) {
employeenames.push([item.value.name, item.value.id]);
}).then(function () {
employeenames.sort();
var chars = {};
$.each(employeenames, function (_, item) {
var char = item[0].charAt(0).toUpperCase();
if (!chars[char]) {
chars[char] = $('<optgroup />', {
label: char
}).appendTo('#employeenameBox select');
}
$('<option />', {
text: item[0],
value: item[0]
}).appendTo(chars[char]);
});
});

Related

document.getElementsByName returns null in jquery [duplicate]

How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

how do i make the option selected in append jquery in foreach

How can I make the option selected according to the value I get from value[0] in the loop?
$.each(data, function(key, value) {
$("#cektubuh").append(
`<tr>
<td>
<select name="duration_type[]" class="form-control" required>
// here I want to add the selected option according to $ {value [0]}
<option value="Semester">Semester</option>
<option value="Month">Month</option>
</select>
</td>
</tr>`
});
});
As you have not provided an example of the data, there is no way to know what values are being used here or how they compare. Here is a basic example based on what you have provided.
$.each(data, function(k, v) {
var row = $("<tr>").appendTo($("#cektubuh"));
var cell = $("<td>").appendTo(row);
var sel = $("<select>", {
name: "duration_type[]",
class: "form-control"
}).prop("required", true).appendTo(cell);
$("<option>", {
value: v[0]
}).html(v[0]).prop("selected", true).appendTo(sel);
$("<option>", {
value: "Semester"
}).html("Semester").appendTo(sel);
$("<option>", {
value: "Month"
}).html("Month").appendTo(sel);
});
If it's more complex or has multiple elements, please provide an example of the structure so that a more complete answer can be shown.
if you have value which belongs to options list and you want to show as selected option
just do this.
var value = 'some value';
$('name="duration_type[]"').val(value);
it will show that value as selected.

Complete select list with optgroup in jquery

I have a select list that I complete by this way :
$.each(data, function(index, value) {
$('#Cars').append('<option value="'+ index +'">'+ value +'</option>');
});
The data table look like this : [{"0":"Ford","285":"Ferrari", "427":"Other"}]
I want now add category in my select list. The table will look like this
["Cars":{"0":"Ford","285":"Ferrari", "427":"Other"},"Tractors":{"114":"Ferguson","115":"Others"}}]
Can you help me to make the jquery code I have try some but with no result.
I want my select box look like this in Html :
<optgroup label="Cars">
<option>Ford</option>
<option>Ferrari</option>
<option>Other</option>
</optgroup>
<optgroup label="Tractors">
<option>Ferguson</option>
<option>Other</option>
</optgroup>
You can try loop through your nested hash:
var select = '';
$.each(data, function(key, value) {
select += '<optgroup label="'+ key +'">'
$.each(value, function(k, v) {
select += '<option value="'+ k +'">'+ v +'</option>'
})
select += '</optgroup>'
});
Fiddle
Here is a demo
your initial data should be properly formatteed associative array:
var items = {"Cars":{"0":"Ford","285":"Ferrari", "427":"Other"},"Tractors":{"114":"Ferguson","115":"Others"}};
and using 'for in' loop you solve your task.
for(catName in items)
{
var optGroup = $("<optgroup />", {
label: catName
});
for(propName in items[catName])
{
var option = $("<option />", {
text: items[catName][propName],
value: propName
});
optGroup.append(option);
}
$("#Cars").append(optGroup);
}

Multiple select list instant search is working but need to keep <optgroup> tags

HTML:
<select multiple="multiple" id="list" size="10">
<optgroup label="Group A">
<option>Apple</option>
<option>Banana</option>
</optgroup>
<optgroup label="Group B">
<option>Orange</option>
<option>Kiwi</option>
</optgroup>
</select><br>
<input type="text" id="findItem">
JavaScript:
jQuery(function() {
var opts = jQuery('#list option').map(function() {
return [[jQuery(this).text()]];
});
jQuery('#findItem').keyup(function() {
var rxp = new RegExp(jQuery('#findItem').val(), 'i');
var optlist = jQuery('#list').empty();
opts.each(function() {
if(rxp.test(this[0])) {
optlist.append(jQuery('<option/>').text(this[0]));
}
});
});
});
JSFIDDLE: http://jsfiddle.net/vou3oa58/
The instant search is working just fine, but the titles disappear because empty() just removes all parent and children elements inside the list. I want to keep groups while performing a search and displaying the matches.
You need to use a more structured data object to take into consideration the optgroup nesting when building your canonical "opts" list. For example, with your HTML snippet, opts might look like:
[{'label': 'Group A', opts: ['Apple',...]}, {'label': 'Group B', opts: [...]}, ..]
A loop to build this might look like:
var optList = [];
jQuery('#list optgroup').each(function() {
var $group = $(this),
optgroup = {'label': $group.attr('label'), opts: []};
$group.find('option').each(function() {
optgroup.opts.push(this.innerText);
});
optList.push(optgroup);
});
Then you just iterate through your new data comparing the internal "opts" array values to the input value... of course, building your new optgroup/option markup for any matches you find.
To reset the entire innerHTML of the list and replace it when the list is cleared:
var optionHTML = $("#list")[0].innerHTML;
then to reset the list:
$("#list").html(optionHTML);

How to get all options of a select using jQuery?

How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

Categories