How do I break two form fields into two lines? - javascript

I have the following code:
function v(id){
return $("#"+id).val();
}
var myToken = v("token");
var myData = {
Address: v("Address") +'\n'+ v("building")
};
and it displays values as follows:
236 Adams way bulding 19
In the example above, Address is 236 Adams way and buidling is building 19.
I would like to have the values display as:
236 Adams way
Building 19
How do I modify the script above to get the result we desire?

In HTML, newlines don't show up. You'd need to insert a <br/> in your output text:
function v(id){
return $("#"+id).val();
}
var myToken = v("token");
var myData = {
Address: v("Address") +'<br/>'+ v("building")
};

You'll want to change the \n to <br/>

Related

jquery iteration of xml response

I have xml respnse from ajax call. I want to iterate it.
Below is my xml ouput in SoaUi.
I want output response as below:
50 Water St Oakland USA
101 Emerall New York USA
Sea Point CA USA
Please help me to write response in jQuery.
EDIT:
This is my response in xml:
<ns3:Row>
<ns3:AddressLine1>50 Water St</ns3:AddressLine1>
<ns3:City>Oakland</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
<ns3:Row>
<ns3:AddressLine1>101 Emerall</ns3:AddressLine1>
<ns3:City>New York</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
<ns3:Row>
<ns3:AddressLine1>Sea Point</ns3:AddressLine1>
<ns3:City>CA</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
You can get the information required looping through the elements and storing the information in a string or whatever you find fit.
One solution (mixing jquery and plain javascript) could be as follows:
$(f).each(function (ind, el) {
var line = '';
$(el).children().each(function (ind, nod) {
line += nod.childNodes[0].nodeValue + ' ';
});
console.log(line.slice(0, -1));
});
the variable 'f' contains the XML string retrieved from the server.
You can test it in this fiddle (open the developer's console to see the result printed there).
Hope it helps.
Solution is here.
var geoCompAddress;
$(data).find('ns3\\:Row').each(function() {
geoCompAddress = $(this).find('ns3\\:AddressLine1').text()+ ',' + $(this).find('ns3\\:City').text()+ ',' + $(this).find('ns3\\:Country').text() ;
});

Apps Script - splitting google form checkbox answers by commas

Google form checkbox question combines the selected responses into one column separated by commas. I am trying to send out a confirmation email of these responses, but the email results in a clunk format:
Register: 9:15 AM - 10:00 AM Instructional Technology Tools & Resources (electronic lab notebooks, classroom tech, analytics, etc.), 10:10 AM - 11:00 AM Tools for flipped or hybrid (blended) courses (learning glass, instructional design, Ted, podcast, etc.)
I'd like to replace the comma separator with <br> but haven't been able to figure it out.
I've tried:
register = e.namedValues[headers[4]].split(',');
register = e.namedValues[headers[4]];
workshops = register.replace(",", "<br>");
Any help would be greatly appreciated! Thank you!
for (var i in headers) {
....... .......
register = e.namedValues[headers[4]];
}
if (e.namedValues[headers[i]].toString() != "" ) {
textbody = ....... + register + "<br>"
}
Should be structured like this:
for (var i in headers) {
....... .......
register = e.namedValues[headers[i]].toString();
if (register != "" ) {
textbody = register.replace(/,/g, "<br>");
}
}
You need to perform a global replacement, after converting the array to a string.
function replaceCommas() {
var headers = ['First Name', 'Timestamp', 'Last Name', 'workshops'];
var register = {'First Name': ['Jane', 'Jon', 'Jim', 'Josie'], 'Timestamp': ['6/7/2015 20:54:13'], 'Last Name': ['Doe'], 'workshops': ['learning glass', 'instructional design', 'Ted', 'podcast']};
//register = e.namedValues[headers[4]].split(',');
var keyName = headers[3]; //Arrays are Zero indexed, fourth item is index 3
Logger.log('keyName is: ' + keyName);
var stringOfValues = register[keyName].toString();
Logger.log('stringOfValues: ' + stringOfValues);
var workshops = stringOfValues.replace(/,/g, "<br>");
Logger.log('workshops: ' + workshops);
}
Copy the above function into your script editor, set a breakpoint on something like the first Logger.log() statement, and step into each line. You can see all the values of the variables in the debug window at the bottom of the screen.
To set a breakpoint, click a line number, and a red dot will appear, that's where the code will stop. Then click the icon of the bug. The code will run up to the point of the breakpoint.
Here is a link to the debug documentation:
Google Documentation - Troubleshooting

How to insert a header in csv object data for manage with d3.js

I'm getting data from csv files for manage with d3.js. Now I would like get the data without head and insert that by JavaScript code. Example with head:
date,type,brand,model,price
2014-11-27, electric, tesla, model s , 100000
2014-11-27, diesel, bmw, m3, 90000
2014-12-13, hybrid, toyota, yaris , 20000
I want to get data without header like:
2014-11-27, electric, tesla, model s , 100000
2014-11-27, diesel, bmw, m3, 90000
2014-12-13, hybrid, toyota, yaris , 20000
I get the data like this:
d3.csv("fileOrURLpath", function(error, data) {...});
I tried to insert header making an array and pushing the header in [0] like:
cars[0]= {
date:"",
type:"",
brand:"",
model:"",
price:""
};
It doesn't work. Only for first in [0].
Is there any way to add a header? Without I can't do nothing else.
EDITED
If the file has no header, I can't use d3.csv. Thanks #LarsKotthoff for the information.
Now I tried that:
var headers = ["date","type","brand","model","price"].join(",");
d3.text("myPath", function(error, data) {
data = d3.csv.parse(headers + data); ... });
but still not working fine. The result is something like that:
Object
" 177 ": undefined
" 7": undefined
" seat": undefined
" toledo": undefined
model: " bengaluru"
brand: " in"
date: Sat Dec 13 2014 00:00:00 GMT+0100 (Hora estándar romance)
type: 7
index: 0
price: NaN
price2014-11-27: " 160 "
I got the solution. Thanks to #LarsKotthoff for your help.
Finally I get my data like this:
// My header
var headers = ["date","type","brand","model","price"].join(",");
// First I get the file or URL data like text
d3.text("myPath", function(error, data) {
// Then I add the header and parse to csv
data = d3.csv.parse(headers +"\n"+ data); ... });
Hope that it helps!

Extract numbers and words from address string using jquery

I have an address string which varies from address to address.
var address_string = '6-3-54/A/889, Road no 45, Toli Chowki, Bangalore, Karnataka 700065, India'
How can I separate the following fields from the above address_string using jQuery
6-3-54/A/889
Road no 45
Toli Chowki
Bangalore
Karnataka
700065
India
Why jQuery?
what_you_need = address_string.split(', ')
You can use split function as below.
var arr = address_string.split(',');
Access and print as below:
for(var i=0;i<arr.length;i++)
{
document.write(arr[i]);
}
Please refer this link ( JS Fiddle) will help to solve you problem
You can use below code to get numbers(array) from String :
String.prototype.getNums= function(){
var rx=/[+-]?((\.\d+)|(\d+(\.\d+)?)([eE][+-]?\d+)?)/g,
mapN= this.match(rx) || [];
return mapN.map(Number);
};
var s= 'I want to extract 123 and 456 from this string ';
alert(s.getNums());
You can check Length as below :
alert(s.getNums()[0].toString().length);
// and so on

Extract text from HTML with Javascript

I would like to extract text from HTML with pure Javascript (this is for a Chrome extension).
Specifically, I would like to be able to find text on a page and extract text after it.
Even more specifically, on a page like
https://picasaweb.google.com/kevin.smilak/BestOfAmericaSGrandCircle#4974033581081755666
I would like to find text "Latitude" and extract the value that goes after it. HTML there is not in a very structured form.
What is an elegant solution to do it?
There is no elegant solution in my opinion because as you said HTML is not structured and the words "Latitude" and "Longitude" depends on page localization.
Best I can think of is relying on the cardinal points, which might not change...
var data = document.getElementById("lhid_tray").innerHTML;
var lat = data.match(/((\d)*\.(\d)*)°(\s*)(N|S)/)[1];
var lon = data.match(/((\d)*\.(\d)*)°(\s*)(E|W)/)[1];
you could do
var str = document.getElementsByClassName("gphoto-exifbox-exif-field")[4].innerHTML;
var latPos = str.indexOf('Latitude')
lat = str.substring(str.indexOf('<em>',latPos)+4,str.indexOf('</em>',latPos))
The text you're interested in is found inside of a div with class gphoto-exifbox-exif-field. Since this is for a Chrome extension, we have document.querySelectorAll which makes selecting that element easy:
var div = document.querySelectorAll('div.gphoto-exifbox-exif-field')[4],
text = div.innerText;
/* text looks like:
"Filename: img_3474.jpg
Camera: Canon
Model: Canon EOS DIGITAL REBEL
ISO: 800
Exposure: 1/60 sec
Aperture: 5.0
Focal Length: 18mm
Flash Used: No
Latitude: 36.872068° N
Longitude: 111.387291° W"
*/
It's easy to get what you want now:
var lng = text.split('Longitude:')[1].trim(); // "111.387291° W"
I used trim() instead of split('Longitude: ') since that's not actually a space character in the innerText (URL-encoded, it's %C2%A0 ...no time to figure out what that maps to, sorry).
I would query the DOM and just collect the image information into an object, so you can reference any property you want.
E.g.
function getImageData() {
var props = {};
Array.prototype.forEach.apply(
document.querySelectorAll('.gphoto-exifbox-exif-field > em'),
[function (prop) {
props[prop.previousSibling.nodeValue.replace(/[\s:]+/g, '')] = prop.textContent;
}]
);
return props;
}
var data = getImageData();
console.log(data.Latitude); // 36.872068° N
Well if a more general answer is required for other sites then you can try something like:
var text = document.body.innerHTML;
text = text.replace(/(<([^>]+)>)/ig,""); //strip out all HTML tags
var latArray = text.match(/Latitude:?\s*[^0-9]*[0-9]*\.?[0-9]*\s*°\s*[NS]/gim);
//search for and return an array of all found results for:
//"latitude", one or 0 ":", white space, A number, white space, 1 or 0 "°", white space, N or S
//(ignores case)(ignores multi-line)(global)
For that example an array of 1 element containing "Latitude: 36.872068° N" is returned (which should be easy to parse).

Categories

Resources