This is the code I have
<script>
function validation () {
var x=document.getElementById("user").value;
var y=document.getElementById("user");
var names="<%=names%>";
for (var j=0; j<names.length; j++) {
if (names[j].test(x)) {
//alert(names[j].match(x));
return true;
}
else{
y.focus();
return false;
}
}
}
</script>
This is for a login page,2 fields are there as usual username password.
I am checking if the username is there in the database,he can enter the password or else he cant.But this code doesnt go to the password even if the username is right.
What am I doing wrong?
Suppose the data type of names in java is an String[], the code <%=names%> equals to <%=names.toString()%>.
So when the jsp is rendered, your javascript code will be something like var names="[Ljava.lang.String;#5d888759". Obviously, it not a valid javascript array definition.
Your need to process your java array first. Add the following code to your jsp(above your javascript code):
<%
StringBuilder sb = new StringBuilder();
sb.append("[");
for(String name : names) {
sb.append("'");
sb.append(name);
sb.append("',");
}
if(sb.charAt(sb.length() - 1) == ',') {
sb.setLength(sb.length() - 1); //remove tailing ','
}
sb.append("]");
String strNames = sb.toString();
%>
And then modify your js code to:
var names="<%=strNames%>";
After jsp rendered, your js code will be like:
var names="['foo','bar']";
which is a valid array definition in js. Then it will work.
If the data type of names in java is List<String>, the solution is similar.
I have found the answer.Thnx for the help
this is the answer
function validation() {
var x=document.getElementById("user").value;
var y=document.getElementById("user");
var z=document.getElementById("pass");
var names="<%=names%>";
names= names.replace("[", "").replace("]", "");
names=names.split(", ");
for (var j=0; j<names.length; j++) {
if (names[j].localeCompare(x)==0) {
return true;
}
z.removeAttribute("readonly", 0);
}
alert("You username is not registered on our databsae");
y.focus();
}
check this out
CASE 1
var names='{id:1,key:"Apple"}'; // here names is string
names.key // will give you error
// so you need to parse it
//using the json2.js script:
var obj = JSON.parse(names);
obj.key // will give you Apple
var obj = jQuery.parseJSON(names)// in jquery
Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.
CASE 2
var names={id:1,key:"Apple"}; // here names is object
names.key // will give you Apple
REFERENCE
JSON = > https://github.com/douglascrockford/JSON-js
Related
I'm working on an add-in for excel 2016 using the javascript API. I can successfully get the range into an array and get the values to show in console.log. I've also been able to get the values into a JSON array using JSON.stringify();
I need to manipulate the array to remove the empty values ("").
Can this be accomplished by using regular javascript array methods?
I'm thinking I can display the results back into a different worksheet using a similar approach like i did with var shWk
Here are some snippets of what I'm trying to do:
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
//document.getElementById("date").innerHTML = Date("MAR 30 2017");
$('#deleteTab').click(deleteTab);
$('#preview').click(preview);
$('#publish').click(publish);
});
};
function preview() {
Excel.run(function(ctx) {
//getting the colname from a date range in B2
var colName = ctx.workbook.worksheets.getItem('preview').getRange("B2");
colName.load('values');
return ctx.sync().then(function() {
//converting colname value to string for column name
var wkN = (colName.values).toString();
// displaying on the task pane
document.getElementById("tst").innerText = wkN;
// testing to confirm i got the correct colname
var shWk = ctx.workbook.worksheets.getItem('preview').getRange("B3");
shWk.values = colName.values;
//building the column connection by setting the table name located on a different worksheet
var tblName = 'PILOT_ZMRP1';
var tblWK = ctx.workbook.tables.getItem(tblName).columns.getItem(wkN);
//loading up tblWK
tblWK.load('values');
return ctx.sync().then(function(){
//this is where my question is:
var arry = tblWK.values;
for (var i=0; i < tblWK.length; i++){
if (tblWK.values !== ""){
arry.values[i][0]) = tblWK.values[i][0]
};
};
console.log(arry.length); //returns 185
console.log (arry.values);//returns undefined
tblWK.values = arry;
var tblWeek = tblWK.values;
console.log(tblWeek.length);//returns 185
console.log(tblWK.values);//returns [object Array] [Array[1],Array[2]
})
});
}).catch(function (error) {
console.log(error);
console.log("debug info: " + JSON.stringify(error.debugInfo));
});
}
What am I missing? Can you point me to some resources for javascript array handling in the specific context of office.js?
I want to thank everyone for the time spent looking at this question. This is my second question ever posted on Stack Overflow. I see that the question was not written as clear as it could've been. What i was trying to achieve was filtering out the values in a 1D array that had "". The data populating the array was from a column in a separate worksheet that had empty values (hence the "") and numeric values in it. the code below resolved my issue.
//using .filter()
var itm = tblWK.values;
function filt(itm){
return itm != "";
}
var arry = [];
var sht = [];
var j=0;
var s=0;
arry.values = tblWK.values.filter(filt);
//then to build the display range to show the values:
for (var i=0; i < itm.length-1; i++) {
if (tblWK.values[i][0]){
var arry; //tblWK.values.splice(i,0); -splice did not work, maybe my syntax was wrong?
console.log("this printed: "+tblWK.values[i][0]);
var cl = ('D'+i); //building the range for display
j++; //increasing the range
s=1;//setting the beignning range
var cll = cl.toString();//getRange() must be a string
console.log(cll);//testing the output
}
}
//using the variable from the for loop
var cl = ('D'+s+':D'+j);
var cll = cl.toString();
console.log(cll);//testing the build string
sht = ctx.workbook.worksheets.getItem('Preview').getRange(cll);
sht.values = arry.values; //displays on the preview tab
console.log (arry.values); //testing the output
The question was probably easier said by asking what vanilla javascript functions does office.js support. I found a lot help reading Building Office Add-ins using Office.js by Micheal Zlatkovsky and by reading the MDN documentation as well as the suggested answer posted here.
Regards,
J
I'm not sure what this check is trying to achieve: tblWK.values !== "". .values is a 2D array and won't ever be "".
For Excel, the value "" means that the cell is empty. In other words, if you want to clear a cell, you assign to "". null value assignment results in no-op.
You can just fetch the values form the array that contains null by using for each and can can push the null values into another array.
I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automatically send an email but I need it formatted in a way that my user can edit it later.
There are some check boxes on the form -- but the getResponse() is only populated with the items checked and I need it to show all possible choices. Then I will indicate somehow what was checked.
I can't find a way to see if a text contains a value.
Like in Java with a String, I could do either .contains("9th") or .indexOf("9th") >=0 and then I would know that the String contains 9th. How can I do this with google scripts? Looked all through documentation and I feel like it must be the easiest thing ever.
var grade = itemResponse.getResponse();
Need to see if grade contains 9th.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Update 2020:
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.
I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];
I need to provide data for google APIs table... so I'll send it from servlet to JSP
but how can I access this data in "googles" javascript?
I'll provide sample of another JS - very simple one - just to let me learn how to make what topic says
<script>
function showTable()
{
<%
Object obj = session.getAttribute("list");
List<String> list = new ArrayList<String>();
int size = 0;
if (obj != null) {
list = (ArrayList<String>) obj;
size = (Integer) session.getAttribute("size");
}
for (int i = 0 ; i < size ; i++) {
String value = list.get(i);
%>
alert('<%= i %> = <%= value %> ');
<%
}
%>
}
</script>
It has to print elements of given list... but now it's just a big scriplet with alert inside of it... for to refactor it? I don't like having to much java in JSPs, because servlet is where it should be placed
EDIT: just to sum up - I would prefer "normal" JS for loop here... Generally I'd prefer to minimize java code, and maximize JS
Convert it to JSON in doGet() of a preprocessing servlet. You can use among others Google Gson for this. Assuming that you've a List<Person>:
List<Person> persons = createItSomehow();
String personsJson = new Gson().toJson(persons);
request.setAttribute("personsJson", personsJson);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
(note that I made it a request attribute instead of session attribute, you're free to change it, but I believe it doesn't necessarily need to be a session attribute as it does not represent sessionwide data)
Assign it to a JS variable in JSP as follows:
<script>
var persons = ${personsJson};
// ...
</script>
This way it's available as a fullworthy JS object. You could feed it straight to the Google API.
Now invoke the URL of the servlet instead of the JSP. For example, when it's mapped on an URL pattern of /persons, invoke it by http://localhost:8080/contextname/persons.
JavaScript is executed at client side, and scriptlets, EL, and JSP tags at server side. From the point of view of the server-side code, JavaScript is just generated text, just like HTML markup.
So, if you want to have a JavaScript loop which loops over a JavaScript array in the generated HTML page, you need to generate the JavaScript code which initializes the array, and the JavaScript loop.
Here's the JSP code
var theArray = [<c:forEach items="${sessionScope.list}" var="item" varStatus="loopStatus">'${item}' <c:if ${!loopStatus.last}>, </c:if></c:forEach>];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
This JSP code will generate the following JavaScript code, assuming the list in the session attribute contains "banana", "apple" and "orange":
var theArray = ['banana', 'apple', 'orange', ];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
Make sure, though, to properly escape the values of the list in order to generate valid JavaScript code. For example, if one of the values was "I'm cool", the generated JavaScript would be
var theArray = ['I'm cool', 'apple', 'orange', ];
which is not valid anymore. Use commons-lang StringEscapeUtils.escapeEcmaScript to escape the values.
since the ArrayList is having objects of Strings you can simply use split() method on the value of the array list. Something like as below;
function showTable() {
<%
Object obj = session.getAttribute("list");
List list = null;
if (obj != null) {
list = (ArrayList<String>) obj;
} else list = new ArrayList<String>(); %>
var jsList = <%=list.toString()%>
//remove [] from content
jsList = jsList.replace("[","");
jsList = jsList.replace("]","");
//split the contents
var splitContent = jsList.split(","); //an array of element
for(var i=0;i<splitContent.length;++i) {
alert(splitContent[i]);
}
}
I hope this will help you solve this.