Auto select options in a <select> based on an array Javascript - javascript

I'm working on a project and there is a point which gives me some troubles.
I have a select form autofilled by a script. My select looks up to an array and add the array's values in the select as options.
But now I want to auto select options according to an array.
So I have my array which has some option name inside. Each index correspond to an option. So I would like to select options corresponding to one of the value in the array.
Here is some code :
var attributeFieldCrm = window.parent.Xrm.Page.getAttribute(fieldcrm);
var checkFieldCrmValue = attributeFieldCrm.getValue();
if (checkFieldCrmValue != null) {
console.log('breakpont hit !!!');
var optionSelected = new Array();
optionSelected = checkFieldCrmValue.split("$#");
console.log('les valeurs ont bien été récupérées : ', optionSelected);
var recceuilDesSelections = "";
var result = [];
var options = select && select.options;
var opt;
for (i in optionSelected) {
}
<select id="selectForm" class="selectpicker" multiple data-live-search="true">
</select>
I imagined something like 2 loop for, one going thought the array and for each index I check every options.
thanks for your help !
regards.

It seems that you didn't provide working code, but still:
var sel = document.getElementById('selectForm');
optionSelected.forEach((o)=>{
for (var i = 0;i < sel.options.length;i++) {
if (o == sel.options[i].value) sel.options[i].selected = true;
}
)}

Related

php - How to keep select values after search click

I have a select tag that helps the user filter search results by years. I wish to keep the value of the selected option after clicking on 'search'.
I use php but for the select options I used JS:
var minA = new Date().getFullYear(),
maxA = 1900,
selectA = document.getElementById('selesctDatesOne');
for (var i = maxA; i<=minA; i++){
var optA = document.createElement('option');
optA.value = i;
optA.innerHTML = i;
selectA.appendChild(optA);
}
This is the html:
<select name="yearsFrom" id="selesctDatesOne" ></select>
I saw this thread but I can't figure out how to use it since I set the options via JS.
any idea how to approach this?

Adding options to a select and using select2

I am trying to add options to a select drop down list. I am doing this dynamically with js.
When I do this with one select list it works but I need to dynamically add more select list as the user wants to add more sets.
My one list works just fine like this:
<body>
<select class="js-example-basic-single" name="state"></select>
</body>
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
load_workout_lst({{workout_list | tojson}});
let lst = {{workout_list | tojson}};
let e = document.getElementsByName('state');
console.log(e);
for(var i = 0, l = lst.length; i < l; i++){
var option2 = lst[i];
e[0].options.add(new Option(option2));
}
</script>
I notice when I console.log(e) I get a NodeList. Since I know there is only one item in that list I choose the first one. I access its options and add to it. It works great.
When I add the select menu dynamically I do this:
let exercise = $("#exercise");
var input;
var input = $("<select>").attr("type", "text").attr("name", exerciseName).attr("tabindex", tabIndexNum);
var br = $("<br>");
exercise.append(br);
exercise.append(input);
input.select2();
console.log(input);
for(var i = 0, l = workout_lst.length; i < l; i++){
console.log(workout_lst[i]);
var item = workout_lst[i];
input.options.add(new Option(item));
}
tabIndexNum++;
var workout_lst = [];
function load_workout_lst(lst){
for (let i = 0; i < lst.length; i++){
workout_lst.push(lst[i]);
}
}
Error:
Uncaught TypeError: input.options is undefined
When I console.log(input) here I get an Object. I'm sure that this is my problem I just don't know how to push or add to the Object. Is there a different way I need to be adding to an object? What am I doing wrong here?
I found the official select2 documentation very simple when it comes to managing options. For example, you can use the code snippet below to append and select option. For more details, i have left a reference.
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, true, true);
$('#mySelect2').append(newOption).trigger('change');
Reference:
https://select2.org/programmatic-control/add-select-clear-items

How to make an Option Object be selected as the Default Value

The following code triggers just before a page is loaded. Now I've managed to fill a select with values. But I'm not sure on how to make the first value to be the deafault selected value.
$(document).on('pagebeforeshow', '#searchpage',
//This function is the whole function that runs when the pagebefore event occurs
function () {
//This reads the universities from the api we created
$.getJSON(AddressAccess + "Home/university/format/json",
function (data) {
//The data is sent back in a collection of objects. We need to extract each object and do relative operations
for (var i = 0; i < data.length; i++) {
var university = data[i];
var SelectDropDown = document.getElementById("searchuniversity");
var NewOption = new Option(university.Name, university.UniverstiyID);
if (i == 1) {
SelectDropDown.add(NewOption, Selected);
} else {
SelectDropDown.add(NewOption);
}
};
});
});
Now if i use SelectDropDown.add(NewOption,Selected); Only one option is made as an option in the select and what I want is to just make the first option being read from my json data to be the default option appearing in the select.
Set selectedIndex of SelectDropDown to 1:
if (i == 1) {
SelectDropDown.add(NewOption);
SelectDropDown.selectedIndex = 1;
}
If you're really talking about the very first option from the options list, selectedIndex should be 0. The options array of a select element is zero based.
[edit] based on your comment:
maybe the select already contains a blank option. Try:
if (i < 1) {
SelectDropDown.options.length = 0;
SelectDropDown.add(NewOption);
SelectDropDown.selectedIndex = 0;
}
Just set the defaultSelected property of the element to true:
var newOption = new Option(university.Name, university.UniverstiyID);
newOption.defaultSelected = true;
Or use the parameters of the Option constructor:
var newOption = new Option(university.Name, university.UniverstiyID, true, true);

how do i set selected in Dojo form.select option

Hi there Dojo developers, I have a drop down form.select, and it has few options, how do set an option to be selected. Say I want to have the third option displayed in the select element. I was looking at the dojo docs and I do not see setSelected() or similar.
Thanks
You need to use displayedValue property in addition to value to set the displayed option. Use something like:
selector.set("displayedValue", "the_text_of_the_option");
or you can search the underlying store of your drop down by using :
selectorStore.fetch({query:{id: value}, onComplete: function (items) {
dojo.forEach(items, function(item){
selector.set("displayedValue", "the_text_of_the_option");
selector.set("value", "the_value_of_the_option");
});
}});
Hope that helps.
I found it, it is selector.attr("value", "the_name_of_the_option");
Thank you, this is true and working. I have tested it. However i discovered my bug: I was creating the options dynamically, and when I set .selected = true as soon as I add it to the selector it changes the sated to the first one being selected.
Or if I apply selector.set("displayedValue", "the_text_of_the_option");
It displays visually the selected one but in fact behind the selected is still the first one does not meter if I change it with the above selector.set. So I solved it by manually creating the selected state. This way when I add it letter id stays in the desired one and changes it accordingly.
Snipped here:
//populate latitude selector
match = false;
optionsArr = [];
for(var i = 0; i < namesLength; i++){
for(var j = 0, len2 = latNames.length; j < len2; j++){
if(fieldNames[i].toLowerCase() == latNames[j]){
for (var a = 0; a < namesLength; a++) {
var option = {};
option.label = fieldNames[i];
option.value = i+"";
if(i==a){
option.selected = true;
}
optionsArr.push(option);
}
match = true;
}
}
}
if(match){
var drop1 = dijit.byId("selectLatitude");
drop1.addOption(optionsArr);
}else{
var drop1 = dijit.byId("selectLatitude");
drop1.addOption(options);//options is an array of options created originally
}

get id of checked checkbox in gridview in javascript

I am having checkbox in each itemTemplate of asp:gridview
I want to get ids or values of those many selected checkboxes using only javascript
In pure javascript I'm not sure about platform portability: you'd REALLY want jQuery or some other helper library here.
With jQuery:
var values = [];
var ids = [];
jQuery.each(jQuery("input:checkbox").find(":checked"), function(){
values.push(jQuery(this).val());
ids.push(jQuery(this).attr("id");
});
will give you the ids and values of all the checked checkboxes.
EDIT: ugly, but this might work...
var values = [];
var ids = [];
var inputs = document.getElementsByTagName("input");
var i;
for(i=0;i<inputs.length;i++){
if(inputs[i].hasAttributes() && inputs.getAttribute('type') == "checkbox" && inputs.getAttribute('checked')){
values.push(inputs[i].getAttribute('value'));
ids.push(inputs[i].getAttribute('id'));
}
}
Let me know if that does what you want.
I am not exactly sure on what you are trying to do but this might help you out. This will get all of the inputs on the screen and process only the checked ones.
var inputList = document.getElementsByTagName("input");
var resultsArray = [];
for(var i = 0; i < inputList.length; i++) {
if (inputList[i].getAttribute("checked") == true) {
resultsArray.push(inputList[i]);
}
}
Sorry, forgot to tell you that this would be a list of elements. You will then need to extract them however you want to from resultsArray.

Categories

Resources