Values coming into Dropdown box as one line - javascript

I have a Dropdown box, Which is getting filled by values from mySQL database, here is the part of the script that I am using to fill the drop down.
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id option').append(details.aaData[i].id);
}
and here is HTML,
<select name="package" name="package-id" id="package-id">
<option></option>
</select>
But the dropdown shows the values as 1234 where as I am expecting them as,
1
2
3
4
Any workarounds for this?

try Changing This:
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id option').append(details.aaData[i].id);
}
to this:
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id').append("<option value='"+details.aaData[i].id+"'>"+details.aaData[i].id+"</option>");
}
it looks right now like you may be creating a bunch of option inside the blank option.

Related

How to turn items in a <datalist> into a link?

So what I'm trying to accomplish is give the user a text box where they can type a city name. Based on what they type, US cities matching the text will be populated into a datalist. Once the city they like is showing in the datalist, I want them to be able to click the city and be forwarded to a URL based on the city they've chosen.
I've worked out the first portion, I have the following html:
function locationInputChange() {
var val = $('#locationLookup').val();
if (val === "") return;
if (val.length < 3) return;
console.log(val);
$.post("/ContentService/HomeSearch", {
q: val
}, function(res) {
var dataList = $("#locationlist");
dataList.empty();
if (res.length) {
for (var i = 0, len = res.length; i < len; i++) {
var opt = $("<option>" + res[i].Text + " </option>").attr("value", res[i].Value);
dataList.append(opt);
}
}
}, "json");
}
<input list="locationlist" id="locationLookup" style="width:80%;" oninput="locationInputChange()" />
<datalist id="locationlist">
</datalist>
and here is the js to get the matching results. /ContentService/HomeSearch will return a json list of matching cities.
I have it working to get the matching results and return and populate the datalist with the relevant options, but I'm stuck as to how to create links out of the datalist. I'm not married to the datalist avenue and I'm open to other methods to create the same effect.

Get second, third and so on values

I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}

Filtering array on multiple options to return options in new select

I am supporting some legacy code and having some issues in implementing a new feature.
I have 2 multiple select options, first one showing a list of states, second showing a list of cities. The idea is that the list of cities will be filtered dependant on the selected states in the first select.
Currently the cities are contained in a javascript array which is used in an if statement to attach the relevant options to the select, howeber this only works on a single state selection.
How can I filter the cities on multiple state selections?
I have tried numerous if statement combinations with no luck. My jquery knowledge is obviously lacking and haven't found anything similar in google/stackoverflow - however I appreciate I may be approaching this from the wrong angle.
<form name="newform">
<select multiple size="10" name="getStateSelect" id="getStateSelectID" onchange="GetSeries(document.newform.getStateSelect.options [document.newform.getStateSelect.selectedIndex].value);">
<option value="1">Alaska</option>
<option value="2">Arizona</option>
<option value="3">Californa</option>
</select>
<br />
<br />
<select id="getCitySelect" multiple="multiple" size="10"></select>
</form>
var fsArray = [{id: 1,stateid: 1,cityname: "Anchorage"},
{id: 2,stateid: 1,cityname: "Fairbanks"},
{id: 3,stateid: 1,cityname: "Wasilla"},
{id: 4,stateid: 2,cityname: "Flagstaff"},
{id: 5,stateid: 2,cityname: "Phoenix"},
{id: 6,stateid: 2,cityname: "Tucson"},
{id: 7,stateid: 3,cityname: "Fremont"},
{id: 8,stateid: 3,cityname: "Lakeport"},
{id: 9,stateid: 3,cityname: "Los Angeles"}];
function GetSeries(i) {
var SeriesSelectBox = document.getElementById("getCitySelect");
SeriesSelectBox.options.length = 0;
for (j in fsArray) {
if (fsArray[j].stateid == i) {
var seriesLength = SeriesSelectBox.options.length;
SeriesSelectBox.options[seriesLength] = new Option(fsArray[j].cityname, fsArray[j].id);
}
}
}
http://jsfiddle.net/fcp3h7mw/1/
Any help greatly appreciated!
Thanks
I just added a for loop on the getStateSelectID values to check if each element for selection status, if selected it runs your loop to add the cities.
the fiddle: http://jsfiddle.net/fcp3h7mw/5/
javascript:
var fsArray = [
{id:1,stateid:1,cityname:"Anchorage"},
{id:2,stateid:1,cityname:"Fairbanks"},
{id:3,stateid:1,cityname:"Wasilla"},
{id:4,stateid:2,cityname:"Flagstaff"},
{id:5,stateid:2,cityname:"Phoenix"},
{id:6,stateid:2,cityname:"Tucson"},
{id:7,stateid:3,cityname:"Fremont"},
{id:8,stateid:3,cityname:"Lakeport"},
{id:9,stateid:3,cityname:"Los Angeles"}
];
function GetSeries(i) {
var id = document.getElementById("getStateSelectID");
var SeriesSelectBox = document.getElementById("getCitySelect");
SeriesSelectBox.options.length = 0;
var states = 0;
for (states=0; states < id.length; states++) {
if(id[states].selected){
for (j in fsArray) {
if (fsArray[j].stateid == id[states].value) {
var seriesLength = SeriesSelectBox.options.length;
SeriesSelectBox.options[seriesLength] = new Option(fsArray[j].cityname, fsArray[j].id);
}
}
}
}
}
Markup: I also took out a lot of your function call in the markup
<select multiple size="10" name="getStateSelect" id="getStateSelectID" onchange="GetSeries();">
I've updated your code to be able to select multiple states and display the correct cities.
Essentially, you needed to get a list of options with attribute "selected" and store the option values in an array (onchange)
Afterwards, you would iterate through the new array and match against the values in the array instead of a single value.
Here's the updated code: http://jsfiddle.net/biz79/fcp3h7mw/3/
var fsArray = [
{id:1,stateid:1,cityname:"Anchorage"},
{id:2,stateid:1,cityname:"Fairbanks"},
{id:3,stateid:1,cityname:"Wasilla"},
{id:4,stateid:2,cityname:"Flagstaff"},
{id:5,stateid:2,cityname:"Phoenix"},
{id:6,stateid:2,cityname:"Tucson"},
{id:7,stateid:3,cityname:"Fremont"},
{id:8,stateid:3,cityname:"Lakeport"},
{id:9,stateid:3,cityname:"Los Angeles"}
];
function getSeries() {
var SeriesSelectBox = document.getElementById("getCitySelect");
SeriesSelectBox.options.length = 0;
var arr = getStateSelected();
for (var i = 0; i< arr.length; i++) {
for (var j in fsArray) {
if (fsArray[j].stateid == arr[i]) {
var seriesLength = SeriesSelectBox.options.length;
SeriesSelectBox.options[seriesLength] = new Option(fsArray[j].cityname, fsArray[j].id);
}
}
}
}
function getStateSelected() {
var sel = document.querySelectorAll('#getStateSelectID option');
var arr = [];
for (var i = 0; i< sel.length; i++ ) {
if ( sel[i].selected ) {
arr.push(sel[i].value);
}
}
return arr;
}
Hope this helps. Let me know if you have questions.

Javascript find missing select value

I have the following JavaScript:
var next_user = "1";
i=0;
for (i=0;i<=10;i++)
{
var el = document.getElementById("user_list");
var val = el[i].value;
if (val <= next_user)
{
next_user = i;
}
if (val >= next_user)
{
next_user = i;
}
alert(next_user);
}
and I have following Select box on the screen:
<select id="user_list" onclick="load_user(this)" name="user_list" size="21" style="width:200px;">
<option value="1">Bob</option>
<option value="2">john</option>
<option value="3">Frank</option>
<option value="5">tom</option>
</select>
I can't seem to get it working the way I want it to.
The select box could have 10 users in the list and each of the (options) values are unique (1-10).
as you can see in my select box I am missing value 4. My Javascript code from above is meant to go though the select box and find the first value that is missing. (in my above example, it should reply back with 4 as that is missing) but If Bob is missing then it should reply back with 1.
Well that's what my JavaScript code above should be doing but I can't seem to work out what I am doing wrong. (well I hope I am doing it correct)
does anyone know what I am doing wrong?
(I am not plaining to use any jQuery at this stage)
You should use options property of that select element you extracted.
Example:
<script>
var userList = document.getElementById("user_list");
for (var i=0;i<userList.options.length; i++) {
if (userList.options[i].value != (i+1)) {
alert((i+1)+" is missing");
break;
}
}
</script>
You can use the following code to alert the missing Option
var next_user = 1;
var el = document.getElementById("user_list");
for (i = 0; i < 10; i++) {
var val = parseInt(el[i].value);
if (val > next_user) {
alert(next_user);
break;
} else {
next_user++;
}
}​
Demo: http://jsfiddle.net/joycse06/75kM7/

Multiple checkbox can't access from JavaScript function

I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.
Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.

Categories

Resources