This is my current code. It lists out page titles perfectly, but the links all return 'undefined'.
function func(json) {
var e = document.getElementById('wiki');
var i;
for (i=0; i < json.query.allpages.length; i++) {
e.innerHTML += i + ": " + '' + json.query.allpages[i].title + '' + "<br />";
}
}
function getFromWikipedia() {
var txt = document.getElementById('txt');
var e = document.getElementById('wiki');
var o = document.createElement("script");
o.setAttribute("src", "http://en.wikipedia.org/w/api.php?action=query&list=allpages&format=json&apfrom="+txt.value+"&generator=alllinks&callback=func");
e.appendChild(o);
}
Appending "&prop=links" and/or "&generator=alllinks" to the URL doesn't seem to affect the result.
I would like to know what should I include in this portion:
'<a href="' + json.query.link+ '">'
in order to list the page titles with their respective links.
I have tried "json.query.allpages[i].pageID" and "json.query.alllinks" but it has not been working.
Edit:
Gave up on finding URL and went to do the pageid method instead.
Solved it with this:
e.innerHTML += i + ": " + '' + json.query.allpages[i].title + '' + "<br />";
You can create the link directly using the pageid:
function func(json) {
var e = document.getElementById('wiki');
var i;
for (i=0; i < json.query.allpages.length; i++) {
e.innerHTML += i + ": " + '' + json.query.allpages[i].title + '' + "<br />";
}
}
The fact that you have both list= and generator= in the same query suggests to me that you don't fully understand how generators work in the MediaWiki API.
Basically, a generator is a way to use a list as the source of pages to retrieve properties for. It does not make any sense to use a generator as the input to another list query. That is, you'd normally use generator= with prop=, not with list=. The only reason MediaWiki (seemingly) allows that at all is because:
You can make a query with a page list (or a generator) but no prop= parameter, like this. If you do, you'll just get a minimal default set of properties (title, namespace and page ID) for the pages.
You can also combine a properties query and a list query into a single request, like this. You'll just get the results for both queries, merged into the same JSON/XML/etc. output, but they'll be otherwise completely separate. (You can also make multiple simultaneous list queries that way.)
Thus, when you combine a generator= with a list= query, you'll get both the usual output for the list and a minimal set of properties for the pages matched by the generator. The two outputs will not be connected in any real way, except for being part of the same API response.
Anyway, you wanted to know how to obtain the titles and URLs of all Wikipedia pages with links. Well, as schudel notes in their answer, to get the URLs for some pages you need prop=info with inprop=url; to run this query on all linked pages, you can use generator=alllinks. Thus, you end up with:
https://en.wikipedia.org/w/api.php?action=query&prop=info&inprop=url&generator=alllinks
Note that this gives information about all pages that have links from them. To run the query on all pages with links to them, you need to add the parameter galunique=true:
https://en.wikipedia.org/w/api.php?action=query&prop=info&inprop=url&generator=alllinks&galunique=true
(Yes, this is documented, although not as clearly as it perhaps could be.)
Obviously, the link targets will include a lot of missing pages. The fact that the link sources seemingly also include a missing page with an empty title is presumably due to a faulty record in Wikipedia's link database. This could be fixed by rebuilding the (redundant) links table, but, given Wikipedia's size, this would take quite a bit of time (during which, presumably, the site would have to be locked into read-only mode to avoid further inconsistencies).
To process this data in JavaScript, you could do something like this:
var apiURL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=info&inprop=url&generator=alllinks&callback=myCallback';
function myCallback(json) {
var e = document.getElementById('wiki');
for (var id in json.query.pages) {
var page = json.query.pages[id];
if (typeof(page.missing) !== 'undefined') continue;
e.innerHTML +=
id + ': ' + escapeHTML(page.title) + '<br />';
}
// handle query continuations:
if (json.continue) {
var continueURL = apiURL;
for (var attr in json.continue) {
continueURL += '&' + attr + '=' + encodeURIComponent(json.continue[attr]);
}
doAjaxRequest(continueURL);
}
doAjaxRequest(apiURL + '&continue=');
Note that I've also included a basic mechanism for handling query continuations, since you'll surely need to handle those when using alllinks. Implementing the helper functions escapeHTML() and doAjaxRequest() is left as an exercise. Also note that I haven't actually tested this code; I think it's OK, but there might be bugs that I've missed. It will also produce a ridiculously long list, and probably slow your browser to a crawl, simply because Wikipedia has a lot of pages. For a real application, you'd probably want to introduce some kind of an on-demand loading scheme (e.g. only loading more results when the user scrolls down to the end of the current list).
Related
Please give me a simple tip where to dig!
I have multiple IP's and need to display the location next to each of them.
I have a list of IPS in array via
var table = document.createElement('table');
table.innerHTML = forext;
var ips = [].slice.call(table.querySelectorAll('a[href*="?ip="]')).map(anchor => anchor.textContent).join("\n");
8.8.8.8
8.8.4.4
...
I can get the location of each of them via input box
$('.send').on('click', function(){
$.getJSON('https://ipapi.co/'+$('.ip').val()+'/json', function(data){
$('.city').text(data.city);
$('.country').text(data.country);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="ip" value="8.8.8.8">
<button class="send">Go</button>
<br><br>
<span class="city"></span>,
<span class="country"></span>
BUT what I need is to print the IPs and the location next to it:
So, I have this:
8.8.8.8
8.8.8.8
BUT I need this
8.8.8.8 -Mountain View, US
8.8.8.8 -Mountain View, US
...
How can I proceed the whole array via http://freegeoip.net/json/? Thank you.
Update 1: Trying to make it using: ips[i]
var ipText='Lookup...';
var table = document.createElement('table');
table.innerHTML = forext;
var ips = [].slice.call(table.querySelectorAll('a[href*="?ip="]')).map(anchor => anchor.textContent).join("\n");
var ipLocations = [];
for(i=0;i<ips.length;i++){
$.getJSON('https:/freegeoip.net/json/' + ips[i], function(data) {
// could also use data.country_name, or any other property in the returned JSON
var outputString = data.ips[i] + ' - ' + data.city + ', ' + data.country_code;
ipLocations.push(outputString);
});
}
ipText = ipLocations.join('\n');
message.innerText = ipText;
First of all, you really want your IPs to be an array of strings, not a single string. As such, you should change your declaration for var ips = ... and delete the .join("\n") from the end--that turns your convenient list of IP strings into a single string with the IPs separated by newline characters, which you don't want.
Then, when you have an array of IP addresses of a form something like ips = ['8.8.8.8', '8.8.4.4', ... ];
...then you can get the output you described in the following way:
var ipLocations = [];
for (var ip of ips) {
$.getJSON('https://freegeoip.net/json/' + ip, function(data) {
// could also use data.country_name, or any other property in the returned JSON
var outputString = data.ip + ' - ' + data.city + ', ' + data.country_code;
ipLocations.push(outputString);
});
}
Now you have an array of strings with IP address + location, as you described. If you now want to turn THAT into a single string, you can do ipText = ipLocations.join('\n'); to get the output lines separated by newline characters.
If you're going to be outputting this text into an HTML document though, you might want to join on <br> instead of \n, there are many contexts in which whitespace characters like \n will be ignored and you would end up with all your output on one line.
UPDATE:
There were some very silly mistakes in my original answer, chief among them being that I mixed Python and JavaScript syntax (facepalm). Having fixed them, this code does work. That being said, there are some caveats that need to be mentioned, as well as some errors in your Update 1 code that you should really try to understand.
First, the issues in your code:
You never got rid of the .join("\n") from line 4 where you define ips, so it's still just a string instead of an array of strings. This means that your for-loop is actually looping over each individual character in the ips string, instead of complete IP addresses.
You try to access data.ips[i] inside of the loop. The data variable contains the JSON response to your AJAX request, but automatically converted from a JSON string into an actual JavaScript object by jQuery. It only has the properties that are included in the response. In this case, the response always has an ip property, so you can access data.ip. However, ips is a variable that YOU created--data.ips doesn't exist, so you can't access its indices.
As a side note, if you used the for...of syntax, you would also have a loop variable called ip that you can use instead. However, you need to understand that ip and data.ip are not the same variable, even if they will always have the same value in this case.
The URL starts with "https:/" instead of "https://". This one is actually my fault, I typo'd it in my original answer >_>;
With that out of the way, you brought up a very important point in your comment-- the function $.getJSON() is asynchronous, so (ignoring the other issues) the code as you wrote it in Update 1 will probably not do what you expect. The code after the call to getJSON will keep running even if your AJAX request doesn't have a response yet, so if you immediately access the ipLocs array it might only have some of the output strings yet, or even be empty.
I'm not going to explain how to wait on non-blocking code to you, because that's a completely different question. I'm also worried that it will only make things more confusing, given your apparent level of familiarity with JavaScript. But if you just want a quick solution that gives you the results that you expect, even if it's not at all best practice, then you can use the ajax function instead of getJSON. This allows you to explicitly tell jQuery to send your AJAX request synchronously, meaning it will wait for a response before continuing to run your code. However, you need to be aware that synchronous requests may temporarily lock your browser, preventing any other actions until the request is completed. That version would look like this:
var ipLocations = [];
for (var ip of ips) {
$.ajax({
url: 'https://freegeoip.net/json/' + ip,
async: false,
success: function(data) {
var outputString = data.ip + ' - ' + data.city + ', ' + data.country_code;
ipLocations.push(outputString);
}
});
}
Imagine I have a loaded HTML page which has been already affected by javascript adding/deleting dynamic elements or new classes/attributes/id to elements while initializing(e.g: original source code [html] tag has no classes, after javascript loads [html] tag has class="no-responsive full-with"). Imagine after that I add/amend some id values manually (through my app). And imagine I need to be able to save in database the original source code (without any amends) but with the id attributes I added manually.
Basically I need to add a given id attribute to an element within the source code of an HTML, loaded through PHP.
Do you guys have any idea of how to do such a thing?
There's no simple solution here. The exact nature of the complex solution will be determined by your full set of requirements.
Updated Concept
You've said that in addition to changing things, you'll also be adding elements and removing them. So you can't relate the changed elements to the originals purely structurally (e.g., by child index), since those may change.
So here's how I'd probably approach it:
Immediately after the page is loaded, before any modifications are made, give every element in the a unique identifier. This is really easy with jQuery (and not particularly hard without it):
var uniqueId = 0;
$("*").attr("data-uid", function() {
return ++uniqueId;
});
Now every element on the page has a unique identifier. Next, copy the DOM and get a jQuery wrapper for it:
var clone = $("html").clone();
Now you have a reliable way to relate elements in the DOM with their original versions (our clones), via the unique IDs. Allow the user to make changes.
When you're ready to find out what changes were made, you do this:
// Look for changes
clone.find("*").addBack().each(function() {
// Get this clone's unique identifier
var uid = $(this).attr("data-uid");
// Get the real element corresponding to it, if it's
// still there
var elm = $("[data-uid=" + uid + "]")[0];
// Look for changes
if (!elm) {
// This element was removed
}
else {
if (elm.id !== this.id) {
// This element's id changed
}
if (elm.className !== this.className) {
// This element's className changed
}
// ...and so on...
}
});
That will tell you about removed and changed elements. If you also want to find added elements, just do this:
var added = $(":not([data-uid])");
...since they won't have the attribute.
You can use the information in clone to reconstruct the original DOM's string:
clone.find("[data-uid]").addBack().removeAttr("data-uid");
var stringToSend = clone[0].outerHTML;
(outerHTML is supported by any vaguely modern browser, the latest to add it was Firefox in v11.)
...and of course the information above to record changes.
Live proof of concept
HTML:
<p class="content">Some content</p>
<p class="content">Some further content</p>
<p>Final content</p>
<input type="button" id="makeChange" value="Make Change">
<input type="button" id="seeResults" value="See Results">
JavaScript:
// Probably unnecessary, but I wanted a scoping
// function anyway, so we'll give the parser time
// to completely finish up.
setTimeout(function() {
// Assign unique identifer to every element
var uniqueId = 0;
$("*").attr("data-uid", function() {
return ++uniqueId;
});
// Clone the whole thing, get a jQuery object for it
var clone = $("html").clone();
// Allow changes
$("#makeChange").click(function() {
this.disabled = true;
$("p:eq(1)").attr("id", "p1");
$("p:eq(2)").addClass("foo");
alert("Change made, set an id on one element and added a class to another");
});
// See results
$("#seeResults").click(function() {
this.disabled = true;
// Look for changes
clone.find("*").addBack().each(function() {
// Get this clone's unique identifier
var uid = $(this).attr("data-uid");
// Get the real element corresponding to it, if it's
// still there
var elm = $("[data-uid=" + uid + "]")[0];
// Look for changes
if (!elm) {
display("Element with uid " + uid + ": Was removed");
}
else {
if (elm.id !== this.id) {
display("Element with uid " + uid + ": <code>id</code> changed, now '" + elm.id + "', was '" + this.id + "'");
}
if (elm.className !== this.className) {
display("Element with uid " + uid + ": <code>className</code> changed, now '" + elm.className + "', was '" + this.className + "'");
}
}
});
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
}, 0);
Earlier Answer
Assuming the server gives you the same text for the page every time it's asked, you can get the unaltered text client-side via ajax. That leaves us with the question of how to apply the id attributes to it.
If you need the original contents but not necessarily identical source (e.g., it's okay if tag names change case [div might become DIV], or attributes gain/lose quotes around them), you could use the source from the server (retrieved via ajax) to populate a document fragment, and apply the id values to the fragment at the same time you apply them to the main document. Then send the source of the fragment to the server.
Populating a fragment with the full HTML from your server is not quite as easy as it should be. Assuming html doesn't have any classes or anything on it, then:
var frag, html, prefix, suffix;
frag = document.createDocumentFragment();
html = document.createElement("html");
frag.appendChild(html);
prefix = stringFromServer..match(/(^.*<html[^>]*>)/);
prefix = prefix ? prefix[1] : "<!doctype html><html>";
suffix = stringFromServer.match(/(<\/html>\s*$)/);
suffix = suffix ? suffix[1] : "</html>";
html.innerHTML = stringFromServer.replace(/^.*<html[^>]*>/, '').replace(/<\/html>\s*$/, '');
There, we take the server's string, grab the outermost HTML parts (or use defaults), and then assign the inner HTML to an html element inside a fragment (although the more I think about it, the less I see the need for a fragment at all — you can probably just drop the fragment part). (Side Note: The part of the regular expressions above that identifies the start tag for the html element, <html[^>]*>, is one of those "good enough" things. It isn't perfect, and in particular will fail if you have a > inside a quoted attribute value, like this: <html data-foo="I have a > in me">, which is perfectly valid. Working around that requires much harder parsing, so I've assumed above that you don't do it, as it's fairly unusual.)
Then you can find elements within it via html.querySelector and html.querySelectorAll in order to apply your id attributes to them. Forming the relevant selectors will be great fun, probably a lot of positional stuff.
When you're done, getting back the HTML to send to the server looks like this:
var stringToSend = prefix + html.innerHTML + suffix;
I have a (GIS) project which displays large amounts of customer data (Thousands of records) to clients. Where nescessary/possible/required, we use server side pagination/filtering/data manipulation but there are cases where it is most efficient to send the data in JSON format to the client and let their browser do the filtering.
The amount of data is large, so we format it to save on bandwidth and parsing time - instead of individual objects, we send a structure that includes the attribute names first and then the values in a single flat array. On the client, we rebuild this into more traditional json objects before other processing occurs. eg:
{attrNames:["foo","bar"],values:[1,2,3,4,...]) -> [{foo:1,bar:2},{foo:3,bar:4},...]
The code for doing this looks a little like this:
function toObjectArray(attrNames, values){
var ret = [];
var index = 0;
var numAttrNames = attrNames.length;
var numValues = values.length;
while(index < numValues){
var obj = {};
for(var a = 0; a < numAttrNames; a++){
obj[attrNames[a]] = values[index++];
}
ret.push(obj);
}
return ret;
}
Given that the attributes may change depending on the customer data, is there a way to do this translation that takes advantage of hidden classes in modern javascript engines like V8? I have done some micro benchmarks similar to our use case ( http://jsfiddle.net/N6CrK/1/ ) where working with json such that hidden classes are used is orders of magnitude faster than building the objects as above. I can get some of this boost using "eval" to create objects, but this feels ugly (This is demonstrated in the js fiddle). Is there a better way? Perhaps using some variant of Object.create, or something like it?
You mean something like this right?
function toHiddenObjectArray(attrNames, attrValues){
var numAttrNames = attrNames.length,
numValues = attrValues.length;
function Data( values ) {
for(var v = 0; v < numAttrNames; v++) {
this[attrNames[v]] = values[v];
}
}
var ret=[];
for( var i=0; i<numValues ; i+=numAttrNames ) {
ret.push( new Data( attrValues.slice(i,i+numAttrNames) ) );
}
return ret;
}
You can check our the fiddle here: http://jsfiddle.net/B2Bfs/ (With some comparison code). It should use the same "Hidden Class" (i.e. Data). Not sure how much quicker it is though!
But, if you really want to make your code none blocking, why not load the page, then request the data via AJAX, then run all you code when you get a response.
I can get some of this boost using "eval" to create objects, but this feels ugly
There's a less ugly way using the Function constructor. Also, further optimisations can be done by immediately assigning the values to the properties, instead of initialising them with null and then again iterating through the attrs array like the adHoc does it. You'd just pass each of the rows you get in the response (array? string? byte-whatever?) as a parameter to the factory.
Also I've moved the creation of the factory function out of the create function, so that only one function will be instantiated (and optimized after enough calls to it).
A decent amount of the time in your test loop is spent on the getTotal, so I've optimised this in a similar manner. Not using getTotalAdHoc in testing the optimised solution drastically reduces the measured time (you can test with getTotalOptimum as well).
var factory = new Function("arr", "return{"+attrs.map(function(n, i){
return n+":arr["+i+"]";
}).join(",")+"};");
var getSum = new Function("o","return "+attrs.map(function(n, i){
return "o."+n;
}).join("+")+";");
(updated jsfiddle)
I haven't yet tried moving the complete loop into the generated code, which could avoid a few function calls, but I don't think this is necessary.
For some reason I just recalled this question... and I just came up with a solution that is way dirtier than using eval but which causes a huge speed boost. The downside of it is that code will be similarly little maintainable as when using eval.
The basic idea is: When receiving the attribute names, generate the function code to parse the following data in JavaScript and add it in a <script> tag to the <head>.
Yeah, isn't that dirty? :-)
If performance is so critical for you, it will definitely help you... here's a modified version of your microbenchmak that proves it: http://jsfiddle.net/N6CrK/17/
Some remarks on the code...
The two functions createWithGeneratedFunction and getTotalWithGeneratedFunction are simply wrapper functions that can be used by productive code. All they do is make sure that the <script> with the generated functions is set up and then call it.
function createWithGeneratedFunction(numValues){
makeSureScriptsAreSetUp()
return createWithGeneratedFunctionAdded(numValues);
}
function getTotalWithGeneratedFunction(objs){
makeSureScriptsAreSetUp()
return getTotalWithGeneratedFunctionAdded(objs);
}
The actual workhorse is the makeSureScriptsAreSetUp with the functions it creates. I'll go through it line by line:
function makeSureScriptsAreSetUp() {
if(scriptIsSetUp)
return;
If the required <script> tag was already set up this function will directly return since there is nothing to do for it anymore.
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var theFunctions = "";
This prepares the creation of the required functions. The theFunctions variable will be filled with the code that is going to be put into the <script> tag content.
theFunctions =
"function createWithGeneratedFunctionAdded(numValues) {" +
" var ret = [];" +
" var value = 0;" +
" for(var i = numValues; i-- > 0;) {" +
" ret.push({";
for(var attr in attrs) {
theFunctions +=
" " + attrs[attr] + ": value++,";
}
theFunctions +=
" });" +
" }" +
" return ret;" +
"}" +
"";
This completes the code for the parsing function. Obviously it just "parses" the numbers 0 to numValues in this microbenchmark. But replacing value++ with something like TheObjectThatTheClientSentMe.values[value++] should bring you very close to what you outlined in your question. (Obviously it would make quite a lot of sense to rename value to index then.)
theFunctions +=
"function getTotalWithGeneratedFunctionAdded(objs) {" +
" var ret = 0;" +
" for(var i = objs.length; i-- > 0;) {" +
" var obj = objs[i];" +
" ret += 0";
for(var attr in attrs) {
theFunctions +=
" + obj." + attrs[attr];
}
theFunctions +=
" ;" +
" }" +
" return ret;" +
"}";
This completes the code for the processing function. Since you seem to require several processing functions, especially this code could become somewhat ugly to write and maintain.
script.text = theFunctions;
head.appendChild(script);
scriptIsSetUp = true;
}
In the very end we simply set the <script> tag content to the code we just created. By then adding that tag to the <head>, Chrome's hidden class magic will occur and will make the code VERY fast.
Concerning extensibility: If you have to query different attribute/value sets from the server on the same page, you might want to give each parsing/processing method set unique names. For example, if you first receive attrs = ["foo","bar"] and next attrs = ["foo","bar","baz"] you could concat the underscore-joined attribute name array to the generated function names.
For example, instead of using createWithGeneratedFunctionAdded you could use createWithGeneratedFunctionAdded_foo_bar for the first attribute/value set and createWithGeneratedFunctionAdded_foo_bar_baz for the second attribute/value set. An attr parameter could then be added to the wrapper functions that will be used to generate the correct code line for an eval (yes, here the evil eval would return) to trigger the correct generated function. Obviously, the attr parameter would also be required for the makeSureScriptsAreSetUp function.
I am trying to replace the content of a div tag with a certain value every 50sec via polling and jQuery. And I would like to access the value of that updated div, so I can save a request to the backend.
My problem is that once the content has been replaced, the browser displays it correctly, however the HTML stays the same as the beginning. I'm afraid this is a rather basic question, but I'm really curious about this.
Here I prepared an example to illustrate the issue: http://jsfiddle.net/LJgN6/7/
And you can see it out ot JSfiddle's context to check the final HTML here: http://jsfiddle.net/LJgN6/7/show
I would like to achieve a way to have in the final HTML(i.e. right click, view page source):
num 1.1 replaced with num 1.2
num 2.1 replaced with num 2.2
...
The code that you see in the View Source window is the HTML that was sent to the browser before anything client side was allowed to modify the DOM. If you want to see the source as it is modified by your javascript, you need to inspect the DOM (IE F12, Firebug, etc.)
If you need to access this value that was inserted earlier, using javascript to access the contents of your element (ie. $('#number-2').text()) should return its contents as they are currently in the DOM.
EDIT: Corrected typo
It looks like you're already familiar with jQuery so I would go ahead and head over to the extremely helpful API and take a look at AJAX calls. There is plenty of documentation there that will help you.
http://api.jquery.com/jQuery.ajax/
Here's an idea. Take a look at my fiddle of your problem
$(document).ready(function(){
$('#number-1').html("num " + 1.1);
$('#number-2').html("num " + 2.2);
$('#number-3').html("num " + 3.3);
$('#number-4').html("num " + 4.4);
setInterval(function(){newInfo();}, 3000);
});
function newInfo(){
var firstDiv = $('#number-1');
var secDiv = $('#number-2');
var thdDiv = $('#number-3');
var frthDiv = $('#number-4');
var firstDivInfo = firstDiv.text().substr(4);
var secDivNewInfo = firstDiv.text().substr(4);
var thdDivNewInfo = secDiv.text().substr(4);
var frthDivNewInfo = thdDiv.text().substr(4);
var newNumber = (Math.random() + 1).toFixed(1);
secDiv.html("num " + secDivNewInfo);
thdDiv.html("num " + thdDivNewInfo);
frthDiv.html("num " + frthDivNewInfo);
firstDiv.html("num " + newNumber);
}
I am trying to check a series of buttons to see if they have been selected in order to generate a query string. So far as I can tell, the logic looks something like this:
if ($("input[name='ovr']")[0].checked)
{
...
}
This works, but since I don't want to use a series of if statements to generate the string (because more buttons might be added later, it's inefficient, etc), I generated an array representing the names associated with the buttons (I printed the array; it definitely contains the proper names). When I made a loop to run through each name in the array, however, the console suggested that 'input' was an unrecognized expression. Here is the loop:
for (i = 0; i < myList.length; i = i + 1) {
if ($("/"input[name='" + myList[i] + "']/"")[0].checked) {
string += myList[i] + "=" + myList[i] + "&";
}
}
string is a variable that appends the proper signature(?) onto itself if the button check should return true. myList is the array containing the names.
Unfortunately, I am new to all of this and don't really know where to begin. I did try to google the answer (really a novice here) but I wasn't even quite sure what to search for. I also messed around with the phrasing of the input expression, used different escape characters, etc., to no avail. Neither the HTML nor most of the javascript is mine (it's my supervisor's), so I am doubly lost. Any suggestions you could give would be sincerely appreciated.
Thanks!
Something like this would work (I don't really understand why you tried to add those backslashes, so I only show you the right way):
for (i = 0; i < myList.length; i = i + 1) {
if ($("input[name='" + myList[i] + "']")[0].checked) {
string += myList[i] + "=" + myList[i] + "&";
}
}
One note: if you are generating a query string, don't forget to use encodeURIComponent()!
something like this?
var query = "?";
$('input:checked').each(function(index) {
query += this.name + "=" + this.value + "&";
});
you can modify the selector to get only the checkboxes you need.