Access data from LabelInput using Google Closure - javascript

I am trying to read input got through autocomplete and display it as a alert. After accessing i get undefined as alert instead of the value accessed through labelinput.
The ex.js file is as follows
goog.require('goog.dom');
goog.require('goog.ui.LabelInput');
goog.require('goog.ui.ac');
goog.require('goog.events.EventType');
function autoComplete() {
var jobj = [{"cityname":"Bangalore","cityid":"1"},
{"cityname":"Bellary","cityid":"2"},
{"cityname":"Belgaum","cityid":"3"},
{"cityname":"Bidar","cityid":"4"},
{"cityname":"Mumbai","cityid":"5"},
{"cityname":"Munnar","cityid":"6"},
{"cityname":"Delhi","cityid":"7"},
{"cityname":"Diu/Daman","cityid":"8"}];
var li1 = new goog.ui.LabelInput("Enter City Name");
li1.render(goog.dom.getElement('d1'));
var array1 = new Array();
for (var i=0;i<jobj.length; i++)
{
array1[i] = jobj[i].cityname;
}
var ac2 = goog.ui.ac.createSimpleAutoComplete(
array1, goog.dom.getElement('d1'), false);
goog.events.listen(ac2,
goog.ui.ac.AutoComplete.EventType.UPDATE,
function() { var val2 = (goog.dom.getElement('d1').value);
alert(val2);
});
}
The ex.html file is as follows
<html>
<head>
<script src="../closure-library/closure/goog/base.js"></script> <!--My Closure Library Location -->
<script src="ex.js"></script>
</head>
<body onload="autoComplete();">
<style>
.ac-renderer {
position: absolute;
width: 300px;
background-color: #fff;
border: 1px solid;
}
</style>
<div id="d1">City &nbsp </div><br><br>
</body>
</html>

"goog.dom.getElement('d1')" will return a div element, which will not have a value. The LabelInput renders a control inside of that element when you call
li1.render(goog.dom.getElement('d1'));
You should be using the getValue method of the LabelInput class itself
li1.getValue()
or if you want to access the Input element created during the LabelInput render method, call
li1.getElement().value
Source : http://docs.closure-library.googlecode.com/git/class_goog_ui_LabelInput.html

Related

Detecting a click after a new element is loaded after the DOM

I am trying to create a simple Chrome Plugin - however I have come to an issue.
I am trying to detect a click on a div using a simple getElementById - however as the api call happens after the DOM is loaded the JS cannot 'find' any div's and gives an error and doesn't do anything after I click on the element.
How do I detect the click, after the data from the API has loaded? I have included some of my code below:
Thanks
document.addEventListener('DOMContentLoaded', function () {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function () {
inputBox = document.getElementById("postcodeInput").value
console.log(inputBox)
let xml = new XMLHttpRequest();
xml.open('get', "https://api.getaddress.io/find/" + inputBox + "/?api-key=SECRET&expand=true", false);
xml.send(null);
var data = xml
var arr = xml.responseText
var data = JSON.parse(arr)
var postcode = data.postcode
var addresses = data.addresses
console.log(addresses)
document.getElementById("postcode").innerHTML = postcode;
var text = "";
var i;
for (i = 0; i < addresses.length; i++) {
text += "<div id='addressClick' name=" + i + ">" + addresses[i].line_1 + "</div>" + "<br>";
}
document.getElementById("data").innerHTML = text;
clickFunc()
}, false);
}, false);
function clickFunc() {
var rowBox = document.getElementById("addressClick");
rowBox.addEventListener('click', function () {
console.log('asd');
}, true);
}
HTML
<!doctype html>
<html>
<head>
<title>Address Search</title>
<script src="popup.js"></script>
</head>
<body>
<h3>Address Search</h3>
<input type="text" id='postcodeInput' name="postcodeInput" value="KW1 4YT">
<button id="checkPage">Search</button>
<div class='results'>
<h3>Results - <span id='postcode'></span></h3>
<p id='data'></p>
</div>
</body>
</html>
<style>
body {
width: 200px
}
#addressClick:hover {
color: blue;
cursor: pointer
}
</style>
You can attach an EventListener to all the body and, at every click, detect if the clicked element is the desired one:
document.body.addEventListener('click', event => window.alert(event.target.innerText));
This can sound like an aggressive solution, but it's way less invasive than a MutationObserver

Storing source code of current browser in chrome extension

I am trying to get the source code(HTML code) of the current browser through a chrome extension. I was trying to store this HTML code in a string, but it doesn't seem to work.
http://jsfiddle.net/ufbxge08/2/
<head>
<style>
button {
height: 30px;
width: 100px;
outline: none;
}
</style>
</head>
<body>
<button id="bth1">Predict</button>
<script src="popup.js"></script>
<script src="jquery-2.0.3.js"></script>
<form>
<label id = 'mybtn1'></label>
</form>
JavaScript:
btn1.onclick = function scrapeThePage() {
// Keep this function isolated - it can only call methods you set up in content scripts
var htmlCode = document.documentElement.outerHTML;
var btn = document.getElementById("mybtn1");
btn.innerHTML = htmlCode;
console.log(htmlCode)
}
I expected the code to store the source code in a string but it doesn't seem to work.
If you want to show HTML code inside an HTML element you may need to set the text content (innerText), not the HTML content (innerHTML):
bth1.onclick = function scrapeThePage() {
// Keep this function isolated - it can only call methods you set up in content scripts
var htmlCode = document.documentElement.outerHTML;
var btn = document.getElementById("mybtn1");
btn.innerText = htmlCode;
}
http://jsfiddle.net/1jk94r50/

Utilizing the array value inside JavaScript when creating new object

I'm new with using JavaScript and my colleague introduced me to jQuery. Right now I'm testing how to utilize the variables I declare to create progress bars during runtime, and I can't figure out how I can create a <div> with its respective counter together with the CSS for animating the progress bar.
Please check variable counter2 as it is being treated as a string rather than its value inside.
I hope this make sense to everyone and thank you for checking this item.
function clickme2(){
var values1 = [40,30];
for (counter2 = 0; counter2 <= 1; counter2++) {
var css =$(".progressbar[counter2]{height: 20px; background: #4169E1; width: 0; text-align: center; border: 1px;} ")
$("head").append(css)
var div =$("<br> <p id = progressnum>this is a progress bar [counter2]</p><div class = 'pp'><div class='progressbar[counter2]'> </div></div>");
$("body").append(div);
$('.progressbar').animate(
{
width: values1[counter2] + "%"
},
{
duration: 500
}
);
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<style type='text/css'>
</style>
<body>
<br>
<button id="add" onclick="clickme2()">Add</button>
<br>
<script>
//refer to my javascript code
</script>
</body>
</html>
To use a variable in a string, you either have to concatenate it, or use a template literal. If you just stick it inside a string, it will be treated as a string, as that is how javascript is designed.
//concatenation
var x = 'me';
var aString = 'Please say hello to '+ x;
//template literal
var x = 'me';
var aString = `Please say hello to ${x}`;

How to add onfocus function to js instead of add it in textarea tag

Hello every one i have below code and i need to to add onfocus function in javascript instead of adding it in textarea tag because it is not secure if i add it in textarea tag
Also make js code work by class of textarea (class="limittext")
<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">
textarea{
width:400px;
height:200px
}
</style>
<script type="text/javascript">
var alert_title='Input Restriction';
function limitTextarea(el,maxLines,maxChar){
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}
function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}
Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};
function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>
<script language="vbscript" type="text/vbs">
set_ie_alert()
Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function
</script>
</head>
<body>
<textarea class="limittext" onfocus="limitTextarea(this,2,0)" wrap="off">some text</textarea>
</body>
</html>
You can add the event listener in javascript with .addEventListener() and get all the elements with the class "limittext" with document.getElementsByClassName(). What you can do is to find all the elements with the class of interest, and then iterate through them and set an event listener to each of them. Something like this should work:
var elements = document.getElementsByClassName('limittext');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('focus', function() {
limitTextArea(elements[i],2,0);
});
}
I don't know if this the best solution or not. I failed to make it work by class but i enabled to make that code work by using ID and do some editions on js code
Thank you for all try to help me
https://jsfiddle.net/zf155z9y/3/
<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">
textarea{
width:400px;
height:200px
}
</style>
<script language="vbscript" type="text/vbs">
set_ie_alert()
Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function
</script>
</head>
<body>
<textarea id="myForm" wrap="off">some text</textarea>
<script type="text/javascript">
var alert_title='Input Restriction';
var x = document.getElementById('myForm');
x.addEventListener("focusin", limitTextarea);
function limitTextarea(){
var el = this;
var maxLines = 5;
var maxChar = 0;
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}
function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}
Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};
function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}
</script>
</body>
</html>

Trouble with Google charts, queries and javascript

I'm trying to create a very simple website consisting of a Google bubble chart overlaid on a background image. The bubble chart is supposed to be generated based on data from a set of Google spreadsheets, and the user can select, through a simple text form, the names of the data points that are to be published. In the code below I have obfuscated the spreadsheet URL, because I don't want to make the data public yet (note however that the viewing privileges of the document are set to public, as required).
The code doesn't work, as no chart is drawn. Obviously there is something fishy going on, because there is never an alert from the collectData method, which handles the query response.
Also, initially I didn't have the draw method and its code was instead in the sendAndDraw method, sans the setTimeout. In that version, I got a Data table not found error on the webpage, but again, the collectData method didn't seem to be called, as it didn't raise an error.
Any suggestions as to what might be the issue? I should add that I am completely new to both javascript and Google developers tools.
EDIT: Following kfa's comment, the form was changed to include a post method. Now I get the Data Table not defined problem once again.
<!DOCTYPE html>
<html>
<head>
<style>
#container{
position: relative;
width: 200px;
height: 200px;
}
#background{
width: 100%;
height: 100%;
}
#bubbleChart{
width: 100%;
height: 100%;
}
</style>
<title>gRNA</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages' : ['corechart']});
google.charts.setOnLoadCallback(function() {initialize()});
var dataSourceUrls = [
'https://docs.google.com/spreadsheets/d/foo/edit#gid=0&headers=1'
];
var nSheets = dataSourceUrls.length;
var query;
var bubbleDataArray = [];
var bubbleData;
function initialize() {
//Currently not doing anything here
}
//Takes a list of names as a comma separated list.
function sendQueries(nameString) {
var queryString = generateQuery(nameString);
for(i = 0; i < nSheets; i++) {
query = new google.visualization.Query(dataSourceUrls[i]);
query.setQuery(queryString);
query.send(collectData);
query.abort();
}
}
//Generates the query string for the selected names.
function generateQuery(nameString) {
nameString = nameString.split(",");
var nNames = nameString.length;
var queryString = [];
queryString.push("select F, D, E, B ");
queryString.push("where F matches ");
queryString.push(nameString[0]);
for(i = 1; i < nNames; i++) {
queryString.push("or ");
queryString.push(nameString[i]);
}
return queryString.join("");
}
//Collect and manage the query responses.
function collectData(response) {
alert('Hi!');
if(response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' +
response.getDetailedMessage());
return;
}
var data = response.getDataTable();
if(data.getNumberOfRows() > 0) {
bubbleDataArray.push(data);
}
}
function sendAndDraw(nameString) {
bubbleDataArray = [];
sendQueries(nameString);
setTimeout(draw,2000);
}
function draw() {
bubbleData = bubbleDataArray[0];
var nTables = bubbleDataArray.length;
for(i = 1; i < nTables; i++) {
bubbleData = google.visualization.data.join(bubbleData,
bubbleDataArray[i], 'full', [[0,0]],
[1,2,3], [1,2,3]);
}
var container = document.getElementById('bubbleChart');
var bubbleChart = new google.visualization.BubbleChart(container);
var options = {
'backgroundColor':'transparent'
}
bubbleChart.draw(bubbleData,options);
}
function plot() {
sendAndDraw(document.getElementById('nameSel').value);
}
</script>
</head>
<body>
<form onsubmit="plot(); return false;" method="post">
<input type="text" id="nameSel"/>
<input type="submit" value="Plot"/>
</form>
<br />
<div id="container">
<div id="background"></div>
<div id="bubbleChart"></div>
</div>
</body>
</html>

Categories