JavaScript / JQuery to load JSON data into HTML5 dynamic drop-down - javascript

I have been trying to get this right and nothing I am doing is working. I made a hard-coded version of a dynamic drop down menu where the second field (State) provides information based on conditions set forth by the selection of the first field (Country).
Here is the hard coded html and JavaScript file:
form.html
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="sampleForm.js"</script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="sampleForm" enctype='application/json'>
<option id='country'>Select Your Country</option>
</form>
</body>
</html>
populate.js:
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML="";
if(s1.value=="Canada"){
var getStates = ["|","alberta|Alberta", "britishColumbia|British Columbia", "manitoba|Manitoba", "newBrunswick|New Brunswick", "newfoundlandAndLabrador|Newfoundland and Labrador", "northwestTerritories|Northwest Territories", "novaScotia|Nova Scotia", "nunavut|Nunavut", "ontario|Ontario", "princeEdwardIsland|Prince Edward Island", "quebec|Quebec", "saskatchewan|Saskatchewan", "yukonTerritory|Yukon Territory"];
} else if(s1.value=="Pakistan"){
var getStates = ["|","balochistan|Balochistan", "northWestFrontierProvince|North-West Frontier Province", "punjab|Punjab", "sindh|Sindh", "islamabadCapitalTerritory|Islamabad Capital Territory", "federallyAdministeredTribalAreas|Federally Administered Tribal Areas"];
} else if(s1.value=="USA"){
var getStates = ["|","alabama|Alabama", "alaska|Alaska", "arizona|Arizona", "arkansas|Arkansas", "california|California", "colorado|Colorado", "connecticut|Connecticut", "delaware|Delaware", "districtOfColumbia|District of Columbia", "florida|Florida", "georgia|Georgia", "hawaii|Hawaii", "idaho|Idaho", "illinois|Illinois"];
}
for(var myState in getStates){
var pair = getStates[myState].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
I have a JSON file that has Country keys and State values. I want to call the keys and values into the dropdown menu options. Based on the answer I found at
$(document).ready(function() {
var data = countryState.json;
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the new html file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a JavaScript file referenced by the html file:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the JSON file:
http://learn.ryanschostag.com/json-file-of-countries-and-states/
My new JavaScript file is based on the answer by Andrew Whitaker at I need help populating my dropdown with my JSON response.
My JSON file was found at gitHub.
I have tried making the src of my form the JSON file. I tried a lot of things for about an hour now, and can't get the data to populate to the drop-down menus, let alone make them dynamic based on conditions.
I don't know how to code the conditions if / else statements and functions relating to calling the JSON data and passing it to the drop down options.
Please help!
Thank you!

Related

Updating or inserting data from a Spreadsheet into a Dialog box inside a dropdown

Goal: The purpose is that a sheet will contain information, this information is placed inside a namedrange, the namedrange will be dynamic (the entire column is given a namedrange).
I created a html popup which contains a dropdown list. This dropdown list must contain the list of information from the namedrange.
I am unable to understand how this is to be done. Here is the code below:
function fncOpenMyDialog() {
var htmlDlg = HtmlService.createHtmlOutputFromFile('HTML_myHtml')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'New File');
};
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var ui = SpreadsheetApp.getUi();
ui.createMenu('New')
.addItem('New Save File Extension','fncOpenMyDialog')
.addToUi();
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select name="nameYouWant" placeholde="File Type">
<option value="something">Word</option>
<option value="anything">MS Excel</option>
<option value="anything">MS Powerpoint</option>
<option value="anything">MS Slides</option>
</select>
<hr/>
<p>Choose a file, which will then be saved into your Google Drive.</p>
<button onmouseup="closeDia()">Close</button>
<button onmouseup="onOpen()">Save</button>
<script>
window.closeDia = function() {
google.script.host.close();
};
window.saveDia = function() {
onOpen();
};
</script>
</body>
</html>
As you can see in my html file, that the extensions are currently hardcoded.
I am trying to make this dynamic, how do I achieve this?
I believe your goal as follows.
You want to put the values to the dropdown list by retrieving from the named range of the Spreadsheet.
In this case, is the named range the same with this thread?
For this, how about this answer?
Modification points:
From google.script.host.close(), I understood that the HTML file of HTML_myHtml is included in the Google Apps Script project. By this, I would like to propose to achieve your goal using google.script.run.
If the named range is the same with your previous question, you can use it by modifying a little.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML and JavaScript side: HTML_myHtml
Please modify HTML_myHtml as follows.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="select" name="nameYouWant" placeholde="File Type"></select>
<hr />
<p>Choose a file, which will then be saved into your Google Drive.</p>
<button onmouseup="closeDia()">Close</button>
<button onmouseup="onOpen()">Save</button>
<script>
google.script.run.withSuccessHandler(v => {
const obj = document.getElementById("select");
v.forEach(e => {
const option = document.createElement("option");
option.text = e;
option.value = e;
obj.appendChild(option);
});
}).readNamedRange();
window.closeDia = function() {
google.script.host.close();
};
window.saveDia = function() {
onOpen();
};
</script>
</body>
</html>
Google Apps Script side: Code.gs
At above HTML, readNamedRange() is used. So please put the following script. If you have the same function names, please modify them. In this script, the values are retrieved from the named range of listDown, and sent to HTML side using google.script.run.
function readNamedRange() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var result = activeSheet.getRange("listDown").getValues();
var end = activeSheet.getLastRow();
var values = [];
for (var i = 0; i < end; i++) {
if (result[i][0] != "") {
values.push(result[i][0]);
}
}
return values;
}
Note:
About window.saveDia = function() {onOpen()};, unfortunately, I couldn't understand about what you want to do.
Reference:
Class google.script.run

Search for word and color it

I am trying to search for a word in iframe and color it using angularjs and jquery. For jquery code i took help from #andrew stackoverflow.
In Jquery code if condition is there, controller is not going inside if condition. please help me to solve the problem.
Here is my complete code, which contains angular code and jquery code.
Angular code is working just fine, in the console i am able to see all the consoles, first i am parsing the arrays and taking out only the string required to search in the jquery. After that i am using that search word to search in the the iframe. But i am facing some problem with the jquery code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html ng-app="app">
<head>
<title>
<%=t itle %>
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div ng-controller="ToddlerCtrl">
<h2>Sample</h2>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<iframe src="text.txt" id="myIframe"></iframe>
<script type="text/javascript">
var myApp = angular.module('app', []);
myApp.controller('ToddlerCtrl', function($scope) {
// Define an array of Toddler objects
$scope.toddlers = [
[100, ["sample"]],
[100, ["used"]],
[100, ["tag"]],
[33.33333333333334, ["file"]]
];
for (var key in $scope.toddlers) {
if ($scope.toddlers.hasOwnProperty(key)) {
var temp = JSON.stringify($scope.toddlers[key][1])
var final_string = temp.slice(2, -2);
var searchWord = final_string;
// console.log(searchWord)
$(document).ready(function() {
$('#myIframe').ready(function() {
var $html = $($('#myIframe').contents().find('body').html());
if ($html.contents().text().search(searchWord) != -1) {
// Some problem with the if condition i guess.
// Controller is not entering if condition.
var replaceWith = "<span style='color:red'>" + searchWord + "</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
// alert($scope.toddlers[key][1]);
// console.log("searchWord")
}
}
});
You can do it easily with Jquery, you can use this function on Javascript:
function findAndColorWord(html, word, color){
var indexWordStart = html.indexOf(word);
var wordLength = word.length;
var coloredWord = '<span style="color: '+color+'">'+word+'</span>';
var firstHtmlPart = html.substring(0, indexWordStart - 1);
var secondHtmlPart = html.substring(indexWordStart + wordLength, html.length - 1);
return firstHtmlPart + coloredWord + secondHtmlPart;
}
You only need to get the position of the word in the html of the iframe, that you can get with $("#id-of the iframe")[0].outerHTML , and after insert in that position a span element with the colored style for the word.
I maked a basic example with a Div that works in the same way that with an a iframe, you can see the example here:
https://jsfiddle.net/9zt976uz/2/#&togetherjs=nQoh3LINQG

connecting angularJS to plotly

So I want to use angularJS to get data from a server and plot the data using Plotly. I am running a server in the background. The HTML I am using is shown below. I think it is pretty straight forward.
<!DOCTYPE html>
<html>
<head>
<title>Testign Plotly</title>
<script type="text/javascript" src='plotly.min.js'></script>
<script type="text/javascript" src='jquery.min.js'></script>
<script type="text/javascript" src='angular.min.js'></script>
<script type="text/javascript" src='plotApp.js'></script>
</head>
<body ng-app='myApp'>
<div id="graph" style="width:600px;height:250px;"></div>
<script type="text/javascript" ng-controller='plotXY'>
// var data = [{
// x:[1,2,3,4],
// y:[5,3,6,12],
// }];
Plotly.plot( $('#graph')[0], {{data}} , {margin: {t:0}});
</script>
<hr><div ng-controller='plotXY'>{{data}}</div>
</body>
</html>
I have the angularJS script plotApp.js as shown below, also very simple ...
var app = angular.module('myApp', []);
app.controller('plotXY', function($scope, $http){
$scope.data = {};
$scope.refresh = function(){
$http.get('http://localhost:8080/data').success(function(data){
$scope.data = {};
for(k in data){$scope.data[k] = data[k].map(Number);}
$scope.data = [$scope.data];
});
};
$scope.refresh();
});
Now, The compiled HTML for this (saved from the browser) is shown below ...
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252"><style type="text/css">#charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>
<title>Testign Plotly</title>
<script type="text/javascript" src="Testign%20Plotly_files/plotly.js"></script><style></style>
<script type="text/javascript" src="Testign%20Plotly_files/jquery.js"></script>
<script type="text/javascript" src="Testign%20Plotly_files/angular.js"></script>
<script type="text/javascript" src="Testign%20Plotly_files/plotApp.js"></script>
</head>
<body class="ng-scope" ng-app="myApp">
<div id="graph" style="width:600px;height:250px;"></div>
<script class="ng-scope" type="text/javascript" ng-controller="plotXY">
// var data = [{
// x:[1,2,3,4],
// y:[5,3,6,12],
// }];
Plotly.plot( $('#graph')[0], {{data}} , {margin: {t:0}});
</script>
<hr><div class="ng-scope ng-binding" ng-controller="plotXY">[{"y":[1.26642e-14,2.8044e-14,6.1484e-14,1.33457e-13],"x":[-10,-9,-8,-7]}]</div>
</body></html>
As you can tell, the portion within the div gets updates with the right data. However, that within the script doesn't!
Just so you know, If I use the data variable (the one that is commented out), I am able to see the plot. So Plotly is working.
I want the client to pull data from the server and have plotly display it. I can do it if I create the entire page from the server and send it over. However, I think that this way is much better. However, for some reason, I dont seem to be able to connect the data source in Plotly, to that in angularJS. I would really appreciate some help ...
The Plotly-method of updating the data seems to be through Plotly.restyle():
var update = {x: [[0,1,2], y: [[5,2,4]]};
Plotly.restyle(graphDiv, update, 0);
Just make sure that you use double arrays when you want to update an array. Plotly supports updating multiple traces at once via arrays, so [[0,1,2],[1,3,4]] would update two traces

How to load a local JSON file using JavaScript to update a select list inHTML?? (Expecting simple answers, I'm just a beginner)

This is what I want:
I want to add or remove countries from a 'countries.json' file, which stored in my local. This is just a test to understand json. Please help me.
<html>
<head>
<title></title>
</head>
<body>
<select name="countries" id="countries"></select>
</body>
<script src="dropdown.js"></script>
</html>
Got the answer:
This is how I loaded json using my js:
$(function() {
$('#countries').click(function(){
$.getJSON('dropdown.json', function(data) {
countries = data['countries']
$.each(countries, function(id, country) {
$('select').append('<option value="">' + country["countryName"]+'</option>')
})
});
})
})

String.format not a function

I'm using HTML publisher in hope to have a html page with some javascript codes running on hudson. The HTML code is like this:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../stringformat.js"></script>
<script type="text/javascript">
......
sql=String.format("/.csv? select from table where exchange=`ABC......")
</script>
</head>
However, after a successful build, my html page doesn't show what it suppose to, and as I check the error console, it says
Error: TypeError: String.format is not a function
I have put my stringformat.js into the top folder, as the HTML publisher doesn't seem to allow the file to contain anything other than HTML files.
Can anyone tell me why the String.format is not loaded properly? Thanks!
PS: stringformat.js is the file i got from
http://www.masterdata.se/r/string_format_for_javascript/
The code should be working properly as this piece of code works outside the hudson
try code:
<html>
<head>
<title>String format javascript</title>
<script type="text/javascript">
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var _myString = String.format("hi {0}, i'am {1}","everybody", "stackoverflower");
function show(){
alert(_myString);
}
</script>
</head>
<body>
<input type="button" name="btnTest" id="btnTest" value="Test string format" onclick="show();" />
</body>
</html>

Categories

Resources