Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Peanut and the Gang
Aug 24, 2009

by exmarx

TildeATH posted:

Dots after always makes more sense, but it looks so wrong because nobody does it.

It looks wrong because it is wrong.

Adbot
ADBOT LOVES YOU

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Peanut and the Gang posted:

It looks wrong because it is wrong.

I agree but I do it the other way because my IDE / vim auto indents for me with trailing periods!

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Helado posted:

Thinking about it more today, I misspoke about the 3rd case above where you call:

JavaScript code:
d3.select('body') //12 gets bound to the body, I guess? At any rate, it doesn't show up
    .data([12,3,65,87,45,6,18])
    .enter().append('p')
    .text(function(d){return "I'm " + d});
data() still applies the 7 elements, meaning 6 more are added than were there previously. However, the parent of body is html, meaning the append() appends to the html tag and not the body. So your output looks something like:

code:
<html>
<body></body>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</html>
edit: I've only done 4-5 projects with d3js and the last couple were largely just data crunching and displaying tables. I couldn't really figure out how the examples for building tables worked with the nested calls on selectAll('tr') and selectAll('td'), which led me to those links above.

I hadn't checked the structure before, but you're right: it generates a bunch of ps outside the body. That .data() applies to an element's parent is kinda hosed up but at least the order of operations in the examples is a little clearer.

Helado
Mar 7, 2004

Munkeymon posted:

I hadn't checked the structure before, but you're right: it generates a bunch of ps outside the body. That .data() applies to an element's parent is kinda hosed up but at least the order of operations in the examples is a little clearer.

It's not so much that data applies to the parent as how the object that enter() returns is defined. This part is kind of goofy, but you can think of data() returning an array of all of the element/data pairs that contain both valid data and a valid element.

https://github.com/mbostock/d3/wiki/Selections#wiki-enter posted:

Another way to think about the entering placeholder nodes is that they are pointers to the parent node (in this example, the document body); however, they only support append and insert.

So the goofy part is that when data() creates new elements in the array they are these 'placeholder nodes' that point to the parent node. When you call enter() you are getting just these placeholder nodes. Similarly when exit() is called, it returns all of the existing nodes which are now not required.

I was going to say about how it is one big array, but the thing is that it seems it keeps the currently defined elements separate from the enter() and exit() lists. If you call para.append('hr') in the above example before calling enter(), you get a hr within each existing p. I half expected an extra one to get appended, but this makes more sense in that the order of your enter()/update/exit() won't be as important. So you can think of any action you call on data() is going to be on the valid entries. enter() is the entries with valid data, but not a valid element. And exit() is those without valid data, but they have a valid element.

http://jsfiddle.net/LZsfP/5/

edit: And the reason why I think the placeholder nodes point to the parent is to re-use the existing append function while also preserving hierarchy within selections.

TildeATH
Oct 21, 2010

by Lowtax

Munkeymon posted:

I hadn't checked the structure before, but you're right: it generates a bunch of ps outside the body. That .data() applies to an element's parent is kinda hosed up but at least the order of operations in the examples is a little clearer.

.data() doesn't apply to the parent, it applies to the selection. Your selection in your example is the body, to which you append a data array of 7 elements, and then you use the .enter() function to say "For each data array object for which there is not already a DOM element in my selection, do the following" which you state is to append a <p>. Your selection, though, is on the <body> element, so the <p> is appended to that selection, which exists at the same level in the DOM.

Selections are a bit difficult to get your head around. Like Helado says, they're actually an object that consists of a dataset paired with a set of elements and when there's more of one or the other, then it fires the exit() or enter() behaviors that you've defined. Often, a selection starts out as an empty set of all the <p> elements in a <div> (when you know there are no <p> elements in that <div>) to which you bind data with .data() after which you tell it enter().append('p') so it creates a new <p> for each data object.

Howmuch
Apr 29, 2008
To force myself to finally give in and learn JS, I'm making a small web app with MVC3 and javascript/jquery/knockout on the frontend and I'm completely stumped now.

code:
<dl .. data-bind="foreach: { data: Orders(), as: 'order' }">
    <dd>
        <a data-bind="'attr': { href: '#orderchild' + $index() }" >
        <h2 ... data-bind="'text': order.Name"></h2>
        </a>
		future inner accordion with another observableArray iteration
    </dd>
</dl>
Removed extra stuff for readability.

The code works fine for now and it puts all the order names in an accordion, but the orders array has an Id property as well, and I was wondering how I could get the value of the order.Id and use it to call a function that creates another observableArray that I want to use in a inner-accordion.

The function is already there and works, I just don't know how to get the Id value :(

edit: well, that's what you get for staring at the same problem for too long.. I somehow decided to forget how I got the array to the html in the first place.. :downs:

Howmuch fucked around with this message at 13:02 on Feb 28, 2014

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
So I decided to get fancy and created this monstrosity:

code:
$('#submit').click(function(){
	var radioArray=[];
		radioArray[0]=$('input[name=q1]:checked').val();
		radioArray[1]=$('input[name=q2]:checked').val();
		radioArray[2]=$('input[name=q3]:checked').val();
		radioArray[3]=$('input[name=q4]:checked').val();
	var radioA = radioArray.length;
	var i;
	for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y"){
		
			switch(radioArray[i])
			
			{
			case radioArray[0]:
			alert("radioArray[0] is a yes");
			break;
			
			case radioArray[1]:
			alert("radioArray[1] is a yes");
			break;
					
			case radioArray[2]:
			alert("radioArray[2] is a yes");
			break;
			
			case radioArray[3]:
			alert("radioArray[3] is a yes");		
			};
	}
	
	}
	});

What it should do is capture the values of multiple radio button questions in an array, then loop through the array and if the value is a "y" or yes, it should display a new alert denoting each index with a yes value.

What happens in practice is that as soon as it hits a "y" value, it breaks, which makes sense given that it's a switch statement.

I'm at a brick wall here. How can I loop through an array an alert for each specific index of "y"?


jsfiddle here: http://jsfiddle.net/bhuHe/2/

Raskolnikov2089 fucked around with this message at 23:45 on Mar 5, 2014

excidium
Oct 24, 2004

Tambahawk Soars

You're making it too hard.

code:
$('#submit').click(function(){
	var radioArray=[];
		radioArray[0]=$('input[name=q1]:checked').val();
		radioArray[1]=$('input[name=q2]:checked').val();
		radioArray[2]=$('input[name=q3]:checked').val();
		radioArray[3]=$('input[name=q4]:checked').val();
	var radioA = radioArray.length;
	var i;
	for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y") {
		    alert("radioArray[" + i + "] is a yes");		
		}
	}
	
	});
For a more in depth answer, the reason it wasn't working was pretty simple. By making the switch statement case an actual reference to the array value, you're essentially making the case value the same for every single answer that is yes and the same for every one is that is a no. Suppose you answered yes to question 1. Now when it goes through the switch, no matter what other question you answer yes to, it's going to hit that first case of "y" (not the string "radioArray[0]"). So clicking yes to all 4 questions will just trigger radioArray[0] all 4 times.

If you wanted it to work the way you have it set up you would have to convert each case and the switch value to a string.

code:
$('#submit').click(function(){
	var radioArray=[];
		radioArray[0]=$('input[name=q1]:checked').val();
		radioArray[1]=$('input[name=q2]:checked').val();
		radioArray[2]=$('input[name=q3]:checked').val();
		radioArray[3]=$('input[name=q4]:checked').val();
	var radioA = radioArray.length;
	var i;
	for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y"){
		
			switch("radioArray[" + i + "]")
			
			{
			case "radioArray[0]":
			alert("radioArray[0] is a yes");
			break;
			
			case "radioArray[1]":
			alert("radioArray[1] is a yes");
			break;
					
			case "radioArray[2]":
			alert("radioArray[2] is a yes");
			break;
			
			case "radioArray[3]":
			alert("radioArray[3] is a yes");		
			};
	}
	
	}
	});

excidium fucked around with this message at 00:10 on Mar 6, 2014

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
q1 being in array index 0 is confusing. What do you plan on doing with radioArray after this?

code:
$('#submit').click(function(){
    $('input[type=radio][value=y]:checked').each(function() {
        alert($(this).attr('name')+' is a yes');
    });
});

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

fletcher posted:

q1 being in array index 0 is confusing. What do you plan on doing with radioArray after this?

The alerts were added for debugging. My end goal is to populate a new <div> with additional information triggered for each index with a "y" value. The array with a for loop seemed the easiest way to store then cycle through the "y" values, but I'm open to other suggestions.

Also I wanted to try out arrays since I'm still pretty new to javascript.


code:
for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y") {
		    alert("radioArray[" + i + "] is a yes");		
		}
	}
huh Yeah I really did make that too confusing. thanks.

Raskolnikov2089 fucked around with this message at 00:33 on Mar 6, 2014

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Right on. The alerts can be handy for debugging. Are you familiar with the developer tools that are built into modern browsers? (hit f12!) I like to use console.log('hi there') and console.dir(myObject) when debugging things, it can be a little less annoying than the alerts.

If you do need the array, I would suggest with going with something like this:

code:
$('#submit').click(function(){
    var formArray = $('form').serializeArray();
    console.dir(formArray);
});
Keep hackin' away on it and ask some more questions when you get stuck :)

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

fletcher posted:

.serializeArray();

Thank you for that, that's a much more elegant way to create an array than I was going about it. I think I'm at the point where I know enough to create things, but not a way to do it efficiently. This is surprisingly fun. Maybe I missed my calling.

excidium posted:

If you wanted it to work the way you have it set up you would have to convert each case and the switch value to a string.

This finally clicked this morning. What I ended up with was:

code:
$('#submit').click(function(){
	var radioArray=[];
		radioArray[0]=$('input[name=q1]:checked').val();
		radioArray[1]=$('input[name=q2]:checked').val();
		radioArray[2]=$('input[name=q3]:checked').val();
		radioArray[3]=$('input[name=q4]:checked').val();
	var radioA = radioArray.length;
	var i;
	for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y"){
		    var contentArray=[];
			switch("radioArray[" + i + "]")
			
			{
			case "radioArray[0]":
			contentArray.push("radioArray0");
			break;
			
			case "radioArray[1]":
			contentArray.push("radioArray1");
			break;
					
			case "radioArray[2]":
			contentArray.push("radioArray2");
			break;
			
			case "radioArray[3]":
			contentArray.push("radioArray3");		
			};
            var arrLength=contentArray.length;
            var x;
            for(x=0; x<=arrLength; x++){
                $('#'+ contentArray[x]).css('display','inline');
                };
	}
 
	}
	});

I preset each #radioArray[x] div as "hidden" in my CSS, so now it will change the display to visible only on the "y" valued divs. I'm sure there's a much more efficient way to do this (the above mentioned serializeArray() for starters), but I learned a lot. Thanks both of you for the help.

JSfiddle for reference :http://jsfiddle.net/bhuHe/18/

Raskolnikov2089 fucked around with this message at 19:59 on Mar 6, 2014

DholmbladRU
May 4, 2006
I am attempting to create some functionality which will get and set the document of an iframe. I have been unsuccessful at performing this with jquery...

code:
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script></head>
    <body>
    <iframe sandbox="allow-same-origin allow-scripts" id='a' height="700" width="700" src="http://localhost:8181/website"></iframe> 
    <iframe sandbox="allow-same-origin allow-scripts" id='b' height="700" width="700" src="http://localhost:8181/website"></iframe> 
    </body>
    </html>
When the page loads I need to navigate around in iframe a. At which point I will use javascript or jquery to take the doucment of A and replace B's document with it. Is this even possible? I don't necessarily need to use iframes if there are other options.

Scenario:

1. Page loads, iframe a & b are rendered
2. User navigates inside iframe A to different pages
**below this is functionality I cannot figure out
3. User clicks button to take DOM from iframe a and replace the DOM for Iframe b

This will essentially set the content of iframe b to be where the user had navigated in iframe a

excidium
Oct 24, 2004

Tambahawk Soars
Can you describe why you would want to do this? Why not continue navigating in frame A?

DholmbladRU
May 4, 2006

excidium posted:

Can you describe why you would want to do this? Why not continue navigating in frame A?

Thanks for the reply.

I am integrating an application into another application within an iframe. That iframe resides on a "tab" within the parrent application. When that "tab" is navigated away from and then back to the iframe reloads. So I need to some how keep the content of the iframe stored somewhere. I was thinking if I could just switch the DOM of a hidden iframe back and forth this would work.

Let me know if that doesnt make sense..

DholmbladRU fucked around with this message at 21:54 on Mar 6, 2014

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Raskolnikov2089 posted:

Thank you for that, that's a much more elegant way to create an array than I was going about it. I think I'm at the point where I know enough to create things, but not a way to do it efficiently. This is surprisingly fun. Maybe I missed my calling.


This finally clicked this morning. What I ended up with was:

code:
$('#submit').click(function(){
	var radioArray=[];
		radioArray[0]=$('input[name=q1]:checked').val();
		radioArray[1]=$('input[name=q2]:checked').val();
		radioArray[2]=$('input[name=q3]:checked').val();
		radioArray[3]=$('input[name=q4]:checked').val();
	var radioA = radioArray.length;
	var i;
	for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y"){
		    var contentArray=[];
			switch("radioArray[" + i + "]")
			
			{
			case "radioArray[0]":
			contentArray.push("radioArray0");
			break;
			
			case "radioArray[1]":
			contentArray.push("radioArray1");
			break;
					
			case "radioArray[2]":
			contentArray.push("radioArray2");
			break;
			
			case "radioArray[3]":
			contentArray.push("radioArray3");		
			};
            var arrLength=contentArray.length;
            var x;
            for(x=0; x<=arrLength; x++){
                $('#'+ contentArray[x]).css('display','inline');
                };
	}
 
	}
	});

I preset each #radioArray[x] div as "hidden" in my CSS, so now it will change the display to visible only on the "y" valued divs. I'm sure there's a much more efficient way to do this (the above mentioned serializeArray() for starters), but I learned a lot. Thanks both of you for the help.

JSfiddle for reference :http://jsfiddle.net/bhuHe/18/

There is no need to do a switch/case statement. You already know radioArray[i] is "y" so you just push ("radioArray" + i) into contentArray instead of doing switch/case. Also you should take care to use a code editor that will help you indent and clean your code

Also you can do a lot of this implementing list comprehensions provided by the Array class. They are available unless you need to support older versions of browsers.

Edit: Also you have an off by one error (should be x < arrLength, i < radioA, not <=)

_areaman
Oct 28, 2009

Raskolnikov2089 posted:

So I decided to get fancy and created this monstrosity:

JavaScript code:
$('#submit').click(function(){
	var radioArray=[];
		radioArray[0]=$('input[name=q1]:checked').val();
		radioArray[1]=$('input[name=q2]:checked').val();
		radioArray[2]=$('input[name=q3]:checked').val();
		radioArray[3]=$('input[name=q4]:checked').val();
	var radioA = radioArray.length;
	var i;
	for(i=0; i <= radioA; i++){
		if(radioArray[i]==="y"){
		
			switch(radioArray[i])
			
			{
			case radioArray[0]:
			alert("radioArray[0] is a yes");
			break;
			
			case radioArray[1]:
			alert("radioArray[1] is a yes");
			break;
					
			case radioArray[2]:
			alert("radioArray[2] is a yes");
			break;
			
			case radioArray[3]:
			alert("radioArray[3] is a yes");		
			};
	}
	
	}
	});

What it should do is capture the values of multiple radio button questions in an array, then loop through the array and if the value is a "y" or yes, it should display a new alert denoting each index with a yes value.

What happens in practice is that as soon as it hits a "y" value, it breaks, which makes sense given that it's a switch statement.

I'm at a brick wall here. How can I loop through an array an alert for each specific index of "y"?


jsfiddle here: http://jsfiddle.net/bhuHe/2/

Wow, wayyyyy too complex. I could make this a one-liner or close to it, but I made it a little longer for your comprehension.

jsfiddle

JavaScript code:
$('#submit').click(function(){
    
    var val_to_string_map = {y: 'yes', n: 'no'};
    
    $('#multi-input :checked').each(function(index) {
        var $this = $(this);
        alert($this.attr('name') + " is a " + val_to_string_map[$this.val()]);
    });

});
edit- thanks for syntax highlighting tip

_areaman fucked around with this message at 01:54 on Mar 7, 2014

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

btw in your code tags if you write code=<language> it syntax highlights stuff :holy:

pangstrom
Jan 25, 2003

Wedge Regret

Dolex posted:

You could recreate highcharts with D3.

D3 is a low-ish level SVG toolkit that also includes some helper functions for common data visualization problems (scale, transition, axes, etc)

D3 doesn't do anything for you (though the d3.layout.* kinda does). You are expected to have an understanding of the SVG spec, how the DOM works, and a fair bit of functional javascript.

People complain about the learning curve of D3, when they are really complaining about the learning curve of more advanced javascript features, and the obtuse and unforgiving SVG spec.

Having said that, D3 is immensely powerful and fantastic to use once you have gotten over the initial learning period.

I use D3 in my day job building web-based data analysis tools for a cloud security company.

If you are serious about web based interactive visualization you would be doing yourself a service to learn how to use D3.
This is exactly me. I was sitting on the sidelines for a non-javascript platform to make sweet vector interactive stuff but you can't sit there forever. Basically I can switch the dataset for something someone else (usually Bostock) did or pull off minor tweaks but now I'm in the "hitting the wall" phase. I can only work on it a half hour at a time which means I learn like 1/2 of one thing and then I'm back to being frustrated as I do other things for the day.

Anyway, that's why I just looked for and found this thread. If a d3 thread starts, great, but yeah ultimately I'm just going to have to learn javascript and DOM and (sounds like) SVG so might as well hang out here, too.

sharktamer
Oct 30, 2011

Shark tamer ridiculous
Since I don't see it anywhere near the OP (and that's 5 years old anyway), would anyone be able to reccomend a good book/online learning resource for picking up javascript? I've gone through the codeacademy lessons for js and jquery, but it doesn't seem they've gotten me anywhere near close to starting on even small mess-about apps. Just looking for anything decent that can give me a good foundation.

I'm planning on getting a good grip on javascript, before maybe messing about with coffeescript and some of the more commonly used frameworks. Maybe figure out some of the game creation libraries/frameworks before the next ludum dare comes around. Don't feel the need to point out the advantages of these unless it's really worth knowing before jumping in. Like I said, I'm definitely looking to get a good grip on base js before starting on any of these extras, unless a different approach is recommended nowadays?

sharktamer fucked around with this message at 22:25 on Mar 12, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

sharktamer posted:

Since I don't see it anywhere near the OP (and that's 5 years old anyway), would anyone be able to reccomend a good book/online learning resource for picking up javascript? I've gone through the codeacademy lessons for js and jquery, but it doesn't seem they've gotten me anywhere near close to starting on even small mess-about apps. Just looking for anything decent that can give me a good foundation.

I'm planning on getting a good grip on javascript, before maybe messing about with coffeescript and some of the more commonly used frameworks. Maybe figure out some of the game creation libraries/frameworks before the next ludum dare comes around. Don't feel the need to point out the advantages of these unless it's really worth knowing before jumping in. Like I said, I'm definitely looking to get a good grip on base js before starting on any of these extras, unless a different approach is recommended nowadays?

I unreservedly recommend http://effectivejs.com/ -- Dave is a great writer, understands JS as deeply as any human alive, is a great teacher, and has a lot of experience teaching and working with a variety of languages. I worked on JS engines (including with Dave) for many years, and recommend this to everyone.

Fake edit: the book, I mean. I don't necessarily recommend working on JS engines.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Subjunctive posted:

I unreservedly recommend http://effectivejs.com/ -- Dave is a great writer, understands JS as deeply as any human alive, is a great teacher, and has a lot of experience teaching and working with a variety of languages. I worked on JS engines (including with Dave) for many years, and recommend this to everyone.

Fake edit: the book, I mean. I don't necessarily recommend working on JS engines.

This book is definitely not for beginners. The book assumes you already know JavaScript.

For a beginners resource that is available online try eloquentjavascript. Search that online since I am on my phone and can't provide the link

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

Strong Sauce posted:

This book is definitely not for beginners. The book assumes you already know JavaScript.

For a beginners resource that is available online try eloquentjavascript. Search that online since I am on my phone and can't provide the link

http://eloquentjavascript.net/chapter1.html

It is an awesome resource

quote:

There are those who will say terrible things about JavaScript. Many of these things are true. When I was for the first time required to write something in JavaScript, I quickly came to despise the language. It would accept almost anything I typed, but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, but there is also a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder, because the system will not point them out to you.

However, the flexibility of the language is also an advantage. It leaves space for a lot of techniques that are impossible in more rigid languages, and it can be used to overcome some of JavaScript's shortcomings. After learning it properly, and working with it for a while, I have really learned to like this language.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Strong Sauce posted:

This book is definitely not for beginners. The book assumes you already know JavaScript.

For a beginners resource that is available online try eloquentjavascript. Search that online since I am on my phone and can't provide the link

My recollection is that it starts pretty basic, but I don't have my copy to hand. Eloquent is also great, definitely.

sharktamer
Oct 30, 2011

Shark tamer ridiculous
Thanks for the suggestions everyone. I'll read both, eloquent first.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

sharktamer posted:

Thanks for the suggestions everyone. I'll read both, eloquent first.

Since you're a beginner, you should immediately get into the habit of using a linter. If nothing has changed in the last year, JSHint is probably the best best there. JSLint is also very good, but extremely opinionated about the structure and formatting of your code.

Also use console.log() instead of alert() for debug messages.

And learning to use breakpoints, watches and the console is really useful for debugging. Place a breakpoint and use watches or the console to observe a variable, or use the console to even change a variable's value on-the-fly.

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

Wheany posted:

Since you're a beginner, you should immediately get into the habit of using a linter. If nothing has changed in the last year, JSHint is probably the best best there. JSLint is also very good, but extremely opinionated about the structure and formatting of your code.

If you're up to using an IDE (trust me, as a sublime text convert, it's not that bad) check out WebStorm (or any of their other products if you're doing cross-language development like PHPStorm, etc)

http://www.jetbrains.com/webstorm/

Full support out of the box for linters and stuff.

Valeyard
Mar 30, 2012


Grimey Drawer
code:
$(document).ready(function() {

$('.searchtools-deleteTopic').click(function(){
    var catid = $(this).attr("data-catid");
    var name = $(this).attr("data-name");
    var user = $(this).attr("data-user");
    var me = $(this)

    $.get('/searchtools/auto_delete_page/', {category_id: catid, name: name, user: user}, function(data){
                   $('#cats').html(data);
                   console.log(data);
                   me.hide();
               });

    console.log("here");
    setTimeout(location.reload(), 100000);
    console.log("here again");
    });
Can anyone tell me why this is refusing to actually wait before carrying out the page refresh? I set the timeout to a huge number just to make sure I wasn't missing anything, but it just refreshes instantly.

This is a problem because it means the js on that page doesn't work properly and it reloads the page before it gets a chance to do the work it needs to do

Peanut and the Gang
Aug 24, 2009

by exmarx
You're executing the function and then passing the result to settimeout.
Try:

code:
setTimeout(function(){
    location.reload()
}, 100000);

or

setTimeout(location.reload, 100000);

Valeyard
Mar 30, 2012


Grimey Drawer

Peanut and the Gang posted:

You're executing the function and then passing the result to settimeout.
Try:

code:
setTimeout(function(){
    location.reload()
}, 100000);

or

setTimeout(location.reload, 100000);

Hmm thanks, it still just seems to blow through it without stopping in either case.

The only reason why I think this is even necessary is that on any random time I try to use the button that the js is for, it will sometimes work, but other times it requires me to manually refresh the page to see the changes

I might be looking in the wrong place for the problem but I dont think so

Peanut and the Gang
Aug 24, 2009

by exmarx
Oh, you're getting owned by the async nature of javascript. Taste the ~({[OWNAGE]})~

What you need to do is put the reload() inside of the $.get callback, like this:
code:
$('.searchtools-deleteTopic').click(function(){
    var catid = $(this).attr("data-catid");
    var name = $(this).attr("data-name");
    var user = $(this).attr("data-user");
    var me = $(this)

    $.get('/searchtools/auto_delete_page/', {category_id: catid, name: name, user: user}, function(data){
         alert('will alert second')
         $('#cats').html(data);
         console.log(data);
         me.hide();
         console.log("here");
         location.reload();
         console.log("here again");
    );
    alert('will alert first')
});
When javascript sees the $.get() call, it triggers the async task, and then keeps going. The callback is queued up to run later when the $.get returns with data. With js you can't really read a script from top to bottom and expect I/O calls to block like other languages do.

Valeyard
Mar 30, 2012


Grimey Drawer
Thank you! That works and makes sense. Well your explanation makes sense, but that seems really annoying. I have had to use only little bits of Javascript in the past week and it has been a nightmare most of the time

Valeyard
Mar 30, 2012


Grimey Drawer
code:
$('.searchtools-research').click(function(){

    var url = $(this).attr("data-topurl");
    var query =$(this).attr("data-query");
    var token =$(this).attr("data-token");
    var source = $(this).attr("data-source");
    var properurl = '/searchtools/topics/' + url + '/';

    console.log(properurl);
    console.log(query);

    window.location = properurl;

    $.post(properurl , {url: url, query:query, csrfmiddlewaretoken:token, source: source}, function(data){     
               });
    });
Another question,

My Django View mandates that when Page B receives a POST it is meant to add some data to the database and then render Page B template. When I perform an action (search) on Page B, it POSTS itself, and then displays the search results.

What I am trying to do is, activate this script from Page A, and POST data to Page B, and then have Page B display the results like normal.

What happens though is that the POST is successful (I can see data being added to the database) but it wont render Page B with the search results and just comes up a blank page.

I am REALLY not sure if this is a JS problem this time though - am I being owned by the asynchronous nature again or does this JS just not make sense to begin with?

IronSaber
Feb 24, 2009

:roboluv: oh yes oh god yes form the head FORM THE HEAD unghhhh...:fap:
I need some help. I'm trying to write a function that will validate the input in a text box with a phone number upon invoking the onblur function of said text box. For some reason I can't get it to work and I have no idea what I'm doing wrong.

The code for the page in question

Any advice or solutions that can be offered will be greatly appreciated.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Valeyard posted:

Thank you! That works and makes sense. Well your explanation makes sense, but that seems really annoying. I have had to use only little bits of Javascript in the past week and it has been a nightmare most of the time

You'll get used to it when you do more javascript. Traditionally everything is asynchronous and you pass around a bunch of callbacks and your code starts getting shaped into an arrow with more and more callbacks inside callbacks. There are ways of "flattening" the code, but I'm not going to go into them.

Valeyard posted:

code:
$('.searchtools-research').click(function(){

    var url = $(this).attr("data-topurl");
    var query =$(this).attr("data-query");
    var token =$(this).attr("data-token");
    var source = $(this).attr("data-source");
    var properurl = '/searchtools/topics/' + url + '/';

    console.log(properurl);
    console.log(query);

    window.location = properurl;

    $.post(properurl , {url: url, query:query, csrfmiddlewaretoken:token, source: source}, function(data){
    });
});
Another question,

My Django View mandates that when Page B receives a POST it is meant to add some data to the database and then render Page B template. When I perform an action (search) on Page B, it POSTS itself, and then displays the search results.

What I am trying to do is, activate this script from Page A, and POST data to Page B, and then have Page B display the results like normal.

What happens though is that the POST is successful (I can see data being added to the database) but it wont render Page B with the search results and just comes up a blank page.

I am REALLY not sure if this is a JS problem this time though - am I being owned by the asynchronous nature again or does this JS just not make sense to begin with?

Is "Page B" "properurl" in above code? If it is, i think your page gets rendered as it should, but it is returned inside that "data" variable in your callback.

Try adding a console.log(data) inside that function, possibly putting a breakpoint there, so you can examine the result.

So:
JavaScript code:
$.post(properurl , {url: url, query:query, csrfmiddlewaretoken:token, source: source}, function(data){
	console.log(data); // also go add a breakpoint here in your browser's development tools
});
If you haven't ever added one, here is how they look like:
Firebug:


Firefox native:


Chrome


IE:


(old) Opera Dragonfly


Just open a debugger of your choice (Press F12 in Chrome, IE or Firefox, Ctrl-shift-I in Opera 12), open the scripts/sources tab in the debugger and click on the row number of the row where you want to add a breakpoint. Next time the code execution reaches that point, it will halt and you can inspect the state of the variables in real time, just by hovering over them in the code window, adding watches, or by writing the variable's name in the console and pressing enter.

fakemirage
Nov 6, 2012

Can't see the haters.

IronSaber posted:

I need some help. I'm trying to write a function that will validate the input in a text box with a phone number upon invoking the onblur function of said text box. For some reason I can't get it to work and I have no idea what I'm doing wrong.

The code for the page in question

Any advice or solutions that can be offered will be greatly appreciated.
I can spot two issues in your validation function that will stop it from running.
Line 85:
code:
if((phoneNumber.value.match(phoneno))
Is missing a closing parentheses (or got one opening parentheses too many).

Line 80:
code:
var phoneNumber =  document.getElementById("phone").value;
This is combination with line 85 above means that you're trying to get the value out of the value, i.e. it's the same as writing:
code:
document.getElementById("phone").value.value.match(phoneno)

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

fakemirage posted:

Line 85:
code:
if((phoneNumber.value.match(phoneno))
Is missing a closing parentheses (or got one opening parentheses too many).

And this is one reason why you use a linter.

Valeyard
Mar 30, 2012


Grimey Drawer

Wheany posted:

You'll get used to it when you do more javascript. Traditionally everything is asynchronous and you pass around a bunch of callbacks and your code starts getting shaped into an arrow with more and more callbacks inside callbacks. There are ways of "flattening" the code, but I'm not going to go into them.


Is "Page B" "properurl" in above code? If it is, i think your page gets rendered as it should, but it is returned inside that "data" variable in your callback.

Try adding a console.log(data) inside that function, possibly putting a breakpoint there, so you can examine the result.

So:
JavaScript code:
$.post(properurl , {url: url, query:query, csrfmiddlewaretoken:token, source: source}, function(data){
	console.log(data); // also go add a breakpoint here in your browser's development tools
});
If you haven't ever added one, here is how they look like:
Firebug:


Firefox native:


Chrome


IE:


(old) Opera Dragonfly


Just open a debugger of your choice (Press F12 in Chrome, IE or Firefox, Ctrl-shift-I in Opera 12), open the scripts/sources tab in the debugger and click on the row number of the row where you want to add a breakpoint. Next time the code execution reaches that point, it will halt and you can inspect the state of the variables in real time, just by hovering over them in the code window, adding watches, or by writing the variable's name in the console and pressing enter.

Hey thanks for this detailed reply. Page B is indeed "properurl". I just checked out "data" using a breakpoint and I can see that the html contained within is actually what I want to see, so I think you are right about it being returned inside "data".

I am looking at the documentation for the jquery post function and I can't see what I should do different. I tried adding a line
code:
$( "#result" ).html( data );
and then tagging Page B with that, but of course it doesn't work

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Valeyard posted:

Hey thanks for this detailed reply. Page B is indeed "properurl". I just checked out "data" using a breakpoint and I can see that the html contained within is actually what I want to see, so I think you are right about it being returned inside "data".

I am looking at the documentation for the jquery post function and I can't see what I should do different. I tried adding a line
code:
$( "#result" ).html( data );
and then tagging Page B with that, but of course it doesn't work

Is the data returned from page B a complete html file, or just a fragment? $("#result").html(data); sets the innerHTML of the element whose id is "result" to the html that is returned, so that might not work if it's a complete page and not just a fragment.

You do have some html element on the page with id="result", right?

Adbot
ADBOT LOVES YOU

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Wheany posted:

Is the data returned from page B a complete html file, or just a fragment? $("#result").html(data); sets the innerHTML of the element whose id is "result" to the html that is returned, so that might not work if it's a complete page and not just a fragment.

You do have some html element on the page with id="result", right?

If he wants it to show the response page, the easiest thing might be to create a hidden form and then just submit it. The browser takes over and there's no more asynchrony to futz with.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply