php - How to keep select values after search click - javascript

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?

Related

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

Auto select options in a <select> based on an array 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;
}
)}

Populating a Select Box with Data from Google Sheet

I have a Google site and am currently using the following script to populate my select box with data from the google sheet that is serving as my database:
<? var stringified = getData(); ?>
<?var data = JSON.parse(stringified)?>
<select size="10" id="userChoice">
<? for (var i = 0; i < data.length; i++) { ?>
<option>
<?= data[i] ?>
<? } ?>
</select>
This loads the page with the select box populated with every entry in the database. I'm wondering if this is the best way to go about it. What I would really like to do is have the contents of the select box be a little more dynamic.
I wrote out a script to filter through (by date) the contents of the Google Sheet, but I can't quite figure out how to have those filtered results show up in the above select box. I've tried several possible solutions, but keep hitting road blocks with them. Below is the function on the client side that passes the dates to the server side (note that I realize nothing in the below scripts would pass the data back to the select box. This is just to show how I am filtering through the data):
//Takes the dates that were entered into the first two date pickers and sends them over to the server side stringified. The server side then uses these dates to filter out jobs not within the given time period.
function dateFilter(){
var date = {};
//dates pusehd into array
date[0] = document.getElementById("startDate").value;
date[1] = document.getElementById("endDate").value;
//array stringified
var dates = JSON.stringify(date);//Convert object to string
google.script.run
.getData2(dates);
Then here is the code that filters through the database on the server side:
function getData2(dates) {
var ss = SpreadsheetApp.openById('1emoXWjdvVmudPVb-ZvFbvnP-np_hPExvQdY-2tOcgi4').getSheetByName("Sheet1");
var date = JSON.parse(dates);
var dateArray = [];
for (var k in date) {//Loop through every property in the object
var thisValue = date[k];//
dateArray.push(thisValue);
};
var startDate = Date.parse(dateArray[0]);
var endDate = Date.parse(dateArray[1]);
var jobReference = [];
var job;
var dateCell1;
var dateCell;
if ((startDate==NaN) || (endDate==NaN)){
for (var i = 2; job!=""; i++){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
};
}
else{
for (var i = 2; job!=""; i++){
dateCell1 = ss.getRange(i,3).getValue();
dateCell = Date.parse(dateCell1);
if (startDate<=dateCell&&endDate>=dateCell){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
Logger.log("here it is"+jobReference);
}
else{
}
}
};
var jR = JSON.stringify(jobReference);
return jR;
}
Now I've tried several things, having a success handler change the line <? var stringified = getData();?> to use getData2 doesn't seem to work (it yells at me that variable I'm trying to parse is undefined on the server side). So I tried putting an if/else in that would only have it parse if the variable was != to undefined, that didn't work either. Any suggestions would be appreciated.
I figured it out! This is functional, but perhaps not best practices, so if someone has any input, feel free to chime in.
So the first bit of code on the client side for the select box I left the same.
The next bit, where I send the dates over to the server side was changed to this:
function dateFilter(){
var sdate = document.getElementById("startDate").value;
var edate = document.getElementById("endDate").value;
google.script.run.withSuccessHandler(dateSuccess)
.getData2(sdate,edate);
}
So, since it was only two variables I took out the part that pushed it to an array. This eliminated the problem of parsing on the server side and thus having an undefined variable. I also added a success handler.
The server side code was left essentially the same, however I did change the for loop slightly. Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); and had it loop though until i<= last. This kept the code from timing out on me.
Next I added the function I used for the success handler:
function dateSuccess(jobs){
document.getElementById('userChoice').options.length = 0;
var data = JSON.parse(jobs)
for (var i = 0; i < data.length; i++) {
var option = document.createElement("option");
option.text = data[i]
var select = document.getElementById("userChoice");
select.appendChild(option);
}
}
Works like a charm!
Scriptlets i.e. <? ?> are compiled and run when the page is created using execute function. They are not for dynamic modification of the web page. To modify the options based on a server returned data, in this case from getData(). You would do something like this
Firstly you set your google.script to call modifyoptions function on success
google.script.run.withSuccessHandler(modifyOptions)
.getData2(dates);
The above will code will automatically pass the return value of getData2 i.e Jr value to modifyOptions function
function modifyOptions(jobReference){
var selOpt = document.getElementById("userChoice")
selOpt.innerHTML ="" // Remove previous options
var options = ""
var data = JSON.parse(jobReference)
for (var i = 0; i < data.length; i++) {
options += "<option>"+data[i] +</option> //New string of options based on returned data
}
selOpt.innerHTML = options //Set new options
}
You can find a working example of how to modify the select-options in javascript here
Hope that helps!

Drop down menu with array, define value of each option

Hello there Stackoverflow!
Today I tried making a drop-down menu with an array. It did work, but the problem that has taken place after this, is to define the values printed by the array.
As of now, this is the code regarding the drop-down menu.
HTML
<select id="selectDestinasjon">
<option>Velg ett sted</option>
</select>
Javascript
var select = document.getElementById("selectDestinasjon");
var options = ["Konsberg", "Trysil", "Beitostølen"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
But I want to give each option a value, that I can later impliment into a calculator, because I want to make a booking service where each of these options has different value and the calculator retrieve info from current selected option, setting a price depending on selected option.
If anything seem unclear or too little detailed, please ask and I'll do my best to explain.
JSFIDDLE
https://jsfiddle.net/a3pe6zcu/
Are you looking for something like this? I have updated your data to hold the price and the name of the place. Now the select has the text as the place and the price as the value. Updated fiddle
var select = document.getElementById("selectDestinasjon");
var options = [{"place": "Konsberg","price":"$20"}, {"place":"Trysil","price":"$30"}, {"place":"Beitostølen","price":"$40"}];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt.place;
el.value = opt.price;
select.appendChild(el);
}

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
}

Categories

Resources