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
Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
There's also JavaScript Allongé if you want to annoy the poo poo out of all your coworkers by writing Lisp in Javascript.

Adbot
ADBOT LOVES YOU

stoops
Jun 11, 2001

Wheany posted:

Do you have any programming experience in other languages?

I never took a real programming course, but I have experience in php and javascript.

I think what I'm missing is not having the basic fundamentals down of programming. I totally get that programming is the same across the board, and that I'd just have to get the new syntax down.

I can read code and can get by, (I still get confused on arrays though.) but I'd like to be sharper.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
I've stumped myself here on some form validation.

I have a few select dropdowns with a text input next to each, like so:

code:
 
<div class="aidInput">
	<select name="loans" class="loans">
		<option value="1">Home</option>
		<option value="2">Auto</option>
	<input type="text" name="loanAmt"  class="amount" placeholder="enter amt here" />
	</select>
</div>

<div class="aidInput">
	<select name="loans" class="loans">
		<option value="1">Home</option>
		<option value="2">Auto</option>
	<input type="text" name="loanAmt"  class="amount" placeholder="enter amt here" />
	</select>
</div>

etc. etc.
The jscript should check to make sure that something has been entered in the .amount input, and if it has, push the .amount value to it's own array, and most importantly, it should capture the value of the <select> next to it and push it to the typeofAid array.

code:
function sumitUp(){
    var typeofAid = [];
    var amtofAid = [];
    $('.amount').each(function(index){
        if($(this).val()!= ''){
            amtofAid.push($(this).val());
            //need to capture value of select in typeofAid if    
            //there is something in .amount field next to it
        }
    }
}
The only thing I can think of is replacing the .each statement with a for loop with a nested if statement, but that seems like it might get really messy.

JSfiddle here: http://jsfiddle.net/EzP7Q/

kedo
Nov 27, 2007

Is this what you're looking for? I'm not pushing the value to the array, but capturing it in a variable (because I was lazy).

http://jsfiddle.net/HM3ve/

You also had some plain old closure syntax errors in your fiddle, just FYI.

\/\/ What he said about your inputs and selects.

kedo fucked around with this message at 19:24 on Jul 17, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Iterate instead over the .aidInput divs instead, and pick out their children to process.

Also, get your <input>s out of your <select>s, there might be kids watching.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

Subjunctive posted:

Iterate instead over the .aidInput divs instead, and pick out their children to process.

Also, get your <input>s out of your <select>s, there might be kids watching.

That works, thanks!

kedo posted:

You also had some plain old closure errors in your fiddle, just FYI.

I'd be grateful for elaboration on this please. I know closure is basically a snapshot of a function and it's environment when it was called saved into memory but that's about the extent of it.

**edit - is it because i'm not capturing the initial $('.amount').each() in a function?

Raskolnikov2089 fucked around with this message at 19:16 on Jul 17, 2014

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
**duplicate my bad

kedo
Nov 27, 2007

Raskolnikov2089 posted:

That works, thanks!


I'd be grateful for elaboration on this please. I know closure is basically a snapshot of a function and it's environment when it was called saved into memory but that's about the extent of it.

**edit - is it because i'm not capturing the initial $('.amount').each() in a function?

See comments in the code below.

JavaScript code:
function sumitUp(){
    var typeofAid = [];
    var amtofAid = [];
    $('.amount').each(function(index){  // On this line you open .each()
        if($(this).val()!= ''){
            amtofAid.push($(this).val());
            //need to capture value of select in typeofAid if    
            //there issomething in .amount field next to it
        }
    } // On this line you close .each(), but you're missing the final )   It should look like this: })	
}
In other words, your code wasn't even running on the page and was throwing a syntax error because you had a function call with an opening parentheses but no closing parentheses.

e: Closure wasn't the right word. Syntax error is more appropriate.

kedo fucked around with this message at 19:23 on Jul 17, 2014

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

kedo posted:

Closure wasn't the right word. Syntax error is more appropriate.

Thanks! It's okay, it led me into a fascinating read of for loops and closure. Sorry for the sloppy copy and paste.

Raskolnikov2089 fucked around with this message at 23:27 on Jul 17, 2014

9-Volt Assault
Jan 27, 2007

Beter twee tetten in de hand dan tien op de vlucht.

stoops posted:

I don't know much javascript or jquery. I mean, I can modify and get things to work, but i'm not comfortable writing it from scratch.

Does anyone have any great solid teaching resources? I don't mind paying for video tutorials, or online classes.

I can't seem to find any community college scripting programs, and i figured the net is the best way to go about it.

if any are highly recommended, I'd appreciate.

http://javascriptissexy.com/how-to-learn-javascript-properly

LP0 ON FIRE
Jan 25, 2006

beep boop
I'd like to have function be called passing in a unique value for i, but whatever listener I activate, when the function is called i always equals 4 - the amount of times that for loop runs.

code:

for(i = 0; i < hotspotLocationsTextAndAudio[winID].length; ++i){
	
	var wordListEle = document.getElementById("dragButton"+winID+"_"+i);
			 
	var func = function(){handleDragStart(this,i)};
			 	
	wordListEle.addEventListener('dragstart', func, false);

}

I'm trying to pass unique arguments by putting in an anonymous function.




edit: I figured it out! I think this is called a closure, not sure:


code:

for(i = 0; i < hotspotLocationsTextAndAudio[winID].length; ++i){

	(function(i) {
	
		var wordListEle = document.getElementById("dragButton"+winID+"_"+i);
			 
		var func = function(){handleDragStart(this,i)};
			 	
		wordListEle.addEventListener('dragstart', func, false);

	}(i));

}

:neckbeard:

LP0 ON FIRE fucked around with this message at 16:18 on Jul 18, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Yeah, you got it, before you were capturing the variable i rather than its then-current value. Calling the function with the argument (which I might name something different for clarity) passes the current value, which is then captured in the inner closure.

LP0 ON FIRE
Jan 25, 2006

beep boop
That is extremely strange and unclear to me not coming from a Javascript background. I see what's happening but it's baffling and not obvious at all.

Peanut and the Gang
Aug 24, 2009

by exmarx
Javascript is for the win!

qntm
Jun 17, 2009
As a general rule you should always be careful when creating functions in loops, for exactly this reason. In a programming language whose closures capture by reference (JavaScript, Python), this behaviour does make sense, and there is unfortunately no other behaviour which makes sense (nor any syntax which would allow you to capture i by value).

You can also do:

JavaScript code:
hotspotLocationsTextAndAudio[winID].forEach(
	function(_, i) {
		var wordListEle = document.getElementById("dragButton"+winID+"_"+i);

		var func = function(){handleDragStart(this,i);};

		wordListEle.addEventListener('dragstart', func, false);
	}
);
Here, you can see that i is a brand new variable each time func is defined, rather than being incremented from one iteration to the next. You will get the desired behaviour.

LP0 ON FIRE
Jan 25, 2006

beep boop

qntm posted:

.. In a programming language whose closures capture by reference (JavaScript, Python) ..

So in a way, without the closure, it's almost like having the variables (i) defined outside the loop and the new functions always referencing those?

Peanut and the Gang
Aug 24, 2009

by exmarx

LP0 ON FIRE posted:

So in a way, without the closure, it's almost like having the variables (i) defined outside the loop and the new functions always referencing those?

Internally, that's exactly what it does.

LP0 ON FIRE
Jan 25, 2006

beep boop

Peanut and the Gang posted:

Internally, that's exactly what it does.

Freaky. I'll try to get used to thinking this way.

Peanut and the Gang
Aug 24, 2009

by exmarx
That's why some people like declaring all their variables at the top of the function even though it makes the code look ugly.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Peanut and the Gang posted:

Javascript is for the win!

This isn't particular to Javascript, it basically always happens with closures. C# has the issue too (http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx). Apparently they've fixed it for the foreach loops by making it so that each run of the loop has a separate value which can be closed over. That doesn't fix it for the standard for loop however.

Incidentally, I believe the Javascript .forEach (not foreach) shouldn't have this problem.

excidium
Oct 24, 2004

Tambahawk Soars

Peanut and the Gang posted:

That's why some people like declaring all their variables at the top of the function even though it makes the code look ugly.

But that's what the JS interpreter does anyway, right? It doesn't matter where it is in the function, it defines all the variables at the top so it's just good practice to get in that habit of defining them up there so that you don't run into a situation where you're expecting one thing and the interpreter does another.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

In ES6 you get let which is lexically scoped to the for's body block, so it behaves the way you want here. Not sure which browsers support it yet, other than Firefox.

qntm
Jun 17, 2009

HappyHippo posted:

This isn't particular to Javascript, it basically always happens with closures. C# has the issue too (http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx). Apparently they've fixed it for the foreach loops by making it so that each run of the loop has a separate value which can be closed over. That doesn't fix it for the standard for loop however.

Incidentally, I believe the Javascript .forEach (not foreach) shouldn't have this problem.

Yes, that's exactly what I just said.

hedgecore
May 2, 2004
Here's more on variable hoisting in JS if you want to read a complete piece about it.
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

LP0 ON FIRE
Jan 25, 2006

beep boop

hedgecore posted:

Here's more on variable hoisting in JS if you want to read a complete piece about it.
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

Thank you.

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
Just a real general question from a JS noob.

I am looking for a small script to embed into html that after a determined time turns the page a set colour, or just shows and image. Then after that is viewed for a set amount of time returns.... The application is for submitting web and graphic design work and avoiding unscrupulous people copying the work and not hiring me, or paying me or whatever.

So is JS the best option for this, will it be easy to do with some googling about?

excidium
Oct 24, 2004

Tambahawk Soars

thegasman2000 posted:

Just a real general question from a JS noob.

I am looking for a small script to embed into html that after a determined time turns the page a set colour, or just shows and image. Then after that is viewed for a set amount of time returns.... The application is for submitting web and graphic design work and avoiding unscrupulous people copying the work and not hiring me, or paying me or whatever.

So is JS the best option for this, will it be easy to do with some googling about?

Your best bet is to get paid up front. Really there is no way you're going to protect graphics online. Your script can be disabled (just turn JS off in the browser) and the file can be lifted. Sure you can do some pretty basic stuff to try and protect your assets, but remember they can all be defeated by someone with just a little know-how.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

excidium posted:

Your best bet is to get paid up front. Really there is no way you're going to protect graphics online. Your script can be disabled (just turn JS off in the browser) and the file can be lifted. Sure you can do some pretty basic stuff to try and protect your assets, but remember they can all be defeated by someone with just a little know-how.

Yeah. Post low-quality thumbnails, send real assets via Dropbox link or whatever when you have the contract in place.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Pfft you don't need functions to enclose variables
JavaScript code:
var s = [];
for (var i = 0; i < 10; i++) {
  try { throw i; }
  catch (i) {
    s.push(function() { console.log(i) })
  }
}
while (s.length > 0) {
  s.shift()();
}

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

:getout: of my language, you savage

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Strong Sauce posted:

Pfft you don't need functions to enclose variables
JavaScript code:
var s = [];
for (var i = 0; i < 10; i++) {
  try { throw i; }
  catch (i) {
    s.push(function() { console.log(i) })
  }
}
while (s.length > 0) {
  s.shift()();
}

jscript bugs are the best

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

jscript bugs are the best

I'll bite, what's the bug?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
The only reason try/catch creates a new scope for the variable is because JScript accidentally implemented it that way.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

The only reason try/catch creates a new scope for the variable is because JScript accidentally implemented it that way.

That's not my recollection, and I think I was the first person to implement JS exceptions. JScript had a bug where it created the variable in the enclosing function's scope, rather than one that matched the duration of the catch block, which I think is the opposite of what you're describing, but exceptions were always specified to create a new scope chain entry with the identifier bound.

15 years, though, so yeah I'd love a reference if you have one.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

Subjunctive posted:

That's not my recollection, and I think I was the first person to implement JS exceptions. JScript had a bug where it created the variable in the enclosing function's scope, rather than one that matched the duration of the catch block, which I think is the opposite of what you're describing, but exceptions were always specified to create a new scope chain entry with the identifier bound.

15 years, though, so yeah I'd love a reference if you have one.
The people we get on these forums :swoon: :sparkles:

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Misogynist posted:

The people we get on these forums :swoon: :sparkles:

Eh. There are no doubt lots of people on SA who could have written the code, I just happened to be right place/right time more than a 20-year-old has any right to expect.

I bet you elicited some serious :rolleye: from Mr Dish, though!

LP0 ON FIRE
Jan 25, 2006

beep boop
Inspector on Safari is reporting that a multidimensional array at a certain index equals undefined and can not evaluate it even though it seems everything is working normally. The error is on this line:

code:

image.src = "http://myurl.com/something/" + keyTimesAndImages[window.IDNum][0][1];

That sets the image source to the correct image. However, specifically the inspector is complaining about keyTimesAndImages[window.IDNum][0] without the third array bracket set.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

And?

LP0 ON FIRE posted:

Inspector on Safari is reporting that a multidimensional array at a certain index equals undefined and can not evaluate it even though it seems everything is working normally. The error is on this line:

code:


image.src = "http://modulusdvd.com/DICHO/modules/audioTextFollow/images/" + keyTimesAndImages[window.IDNum][0][1];


That sets the image source to the correct image. However, specifically the inspector is complaining about keyTimesAndImages[window.IDNum][0] without the third array bracket set.

What is keyTimesAndImages[window.IDNum]'s value? There really isn't much here to go on...

LP0 ON FIRE
Jan 25, 2006

beep boop

Subjunctive posted:

And?


What is keyTimesAndImages[window.IDNum]'s value? There really isn't much here to go on...

Oh sorry. Inspector says it's undefined. It's supposed to be an array.

Ahh, edit. It says

["default", "groceryStore.jpg"]
undefined


edit 2: Okay I think I'm going crazy or there's something weird going on. The first time I told you it said it was undefined that's what I thought I saw until I looked at the console again and pasted what I saw differently. I'm now trying to get the value even after reloading and it just says undefined.

LP0 ON FIRE fucked around with this message at 16:38 on Jul 22, 2014

Adbot
ADBOT LOVES YOU

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

LP0 ON FIRE posted:

Oh sorry. Inspector says it's undefined. It's supposed to be an array.

Ahh, edit. It says

["default", "groceryStore.jpg"]
undefined

In that case [w.IDNum][0][1] should be "groceryStore.jpg", if I'm understanding your post correctly, so I suspect you're not interpreting the error correctly, or else we're misunderstanding each other about what to print here. :shrug:

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