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
Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

Is there a more reliable way of finding the viewable pixel real estate than Prototype's viewport methods? I'm trying to make images shrink to fit the viewport but after a resize, the methods report the document dimensions instead of the dimensions of the window. Since HTML flows down like it's going out of style, I end up with wacky numbers for viewport height (ie bigger than my monitor) and pictures that flow off the screen given otherwise working resize code. This behavior doesn't seem to be entirely consistent since it was working fine at the end of last week in my tests and this morning the same tests are failing.

jQuery(window).height();
jQuery(window).wdth();
:v:

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

hasegawa posted:

Alright, I'm trying to do a simple form validation for a drop box. I want it to give a "Hey choose something stupid" if the value is still "Select One" when the user clicks submit. With the current code, it allows the user to go to the next page regardless of what they choose in the dropdown box. I've tried several different javascript validators, but none of them seem to work with this.

I'm not sure why it isn't working, is it something related to using php ECHO statements instead of regular html <select><option> to create the dropdown list?

How would the browser know what document.term is?

Make sure you are putting in LOTS of debug when learning / trying something new. If you added stuff to your code like so:
code:

function validateForm(){
 window.console.log("Function called");
 window.console.log("I think document.term is", document.term );
window.console.log("I think document.term.selectedIndex  is", document.term.selectedIndex );
 if(document.term.selectedIndex=='0')
 {
    alert("Please select an Item.");
    document.term.focus();
    return false;
  }
  window.console.log("I would have submitted" );
  return false;
}
You'd quickly see what the problem is.

EDIT with solution:

code:
9	<script>
10	function validateForm(){
11	 var el = document.getElementById('termSel');
12    // now we have a reference to that SELECT element
13	 if(el.selectedIndex=='0')
14	 {
15	    el.focus();
16	    return false;
17	  }
18	  return true;
19	}
20	</script>


23	 <form onsubmit="return validateForm()" action="" method="post">
24	  <select name="term" id="termSel">
25	   <option>Pie</option>
26	   <option>Cake</option>
27	   <option>Poop</option>
28	   </select>
29	  <input type="submit" />
30	 </form>

Lumpy fucked around with this message at 22:52 on Apr 25, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

hasegawa posted:

Ooh, I see! I wasn't sure how specific I had to be...if merely stating name=term would work or if I needed more precise. Thanks a million!

No problems. There was a push by MS back when IE6 was new to have any named element be acessable that way ( or something similar like document.all.someName i forget exact syntax ) but the standard is that you have to use document methods to get a reference to elements.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

roweski posted:

Hey guys, completely new to Javascript. Using Flux for mac to create a tv based soundboard for shits and giggles. I've laid it all out, but have no idea how to even go about writing javascript, like, at all..
Help appreciated..

http://javascript.crockford.com/

Buy his book, and read this thread and look for all the other times people have asked this question and follow the suggestions there. Good luck, and have fun learning javascript. It's a neat little language.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Necc0 posted:

start at the beginning of the program and move an alert statement line by line to make sure everything is functioning how it should be.

javascript is kind of a pain that way, but it will work.

edit: I'm kind of wondering what your teacher means by 'semantic' errors as well

Even better, use Webkit's built in javascript debugger ( or whatever the best add-on one for Firefox is these days.. still Firebug? ) and save yourself having to put alerts all over the place!

Also, the first "error" in that script is the formatting...

Lumpy fucked around with this message at 05:17 on May 6, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

LeeJam posted:

Yeah, I know it's awful. I'm only working with what was given to me.

It's supposed to check for negative numbers and get you to re-enter the numbers if you have done so.

Fun thing is, goofy braces can actually cause Bad Stuff in javascript. Take this example shamelessly stolen from Crockford's "java script: The Good Parts" talk...

code:
function returnSomeVal()

{
  return

  {
    someKey: "someVal:"
  }

}

alert( returnSomeVal() );
Guess what you see in your alert.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

MononcQc posted:

I'm writing the JS for a chat app I'm working on in my free time, and I need to have Ids that change according to user submitted data.

This is usually something retarded that I would not do, but I don't see myself having much of a choice.


What would be the best way to escape user_id to avoid any kind of XSS or avoid breaking HTML? Right now I'm using the built-in escape() function, but I'm not sure of how good this is supposed to be.

The "right" answer will depend on what you allow usernames to be. If usernames are email addresses, then you can do strict checking on that for instance. If it's arbitrary, you have a lot more work.

Here's a good little guide I have bookmarked: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Vanadium posted:

document.getElementById("a").onchange = function() { return an_object.onchange(); }; :toot:

There is also call: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/call

code:
an_object.change_now.call(an_object);
You can also use private methods which will execute in the scope of the parent and avoid using "this" altogether if say_hooray is only accessed interally.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

KARMA! posted:

That's even cooler! Hmm, letss see if crockford can give me some great examples of this..

I'm no Crockford, but:

code:
SomeObj = function(){

  var privateVar = 'private';
  var privateFunction = function(){
    alert( privateVar );
  }

  return {
    
     publicVar: "public",
     publicFunc: function(){
       privateFunction();
     }
  }
}

var bob = SomeObj();
bob.publicFunc(); // alerts 'private'

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

peepsalot posted:

Haven't looked at igoogle gadgets at all, so I don't know exactly how it works, but there's two main ways I could see being able to strip out the relevant data.

1) You could try to make a stylesheet that hides all the parts of the page you don't want, append a link element to the page which points to your css sheet, then just show the page in your iframe.
2) You could loop through each element in javascript and extract the relevant info, and append it to the body of your iframe

Number 2 is probably simpler to implement, since there's more things you would need to hide than there are things you want to display.

I inspected the usercp page with firebug and found that each thread title is in a td with class="title". If you are able to use something like jQuery in conjunction with igoogle, then a selector "td.title" makes it easy to grab the relevant elements, then .each can call a function over them:
code:
function processThreadTitle(i,el) {
   // use a regex on the innerhtml or traverse the child nodes of el, 
   // or whatever to get the data, and put it into a newly created element.
}
$("td.title").each(processThreadTitle)

I'd go with #2 as well, and here's the code to grab the data:

code:
jQuery('tr.thread').each( function(){
  var row = jQuery(this);
  var threadTitle = row.find('a.thread_title').text();
  var unreadPosts = row.find('a.count b').text() || 0;
  window.console.log( "thread '" + threadTitle + "' has " + unreadPosts + " unread posts." );
});

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

JingleBells posted:

I'm wondering if there are any recommended resources, books, tutorials and the like related to messing around with the canvas element in javascript? Also anything related to JQuery, I'd like to delve more into JQuery and look at some of the more advanced things you can do with the canvas element. Where I'm working at the moment "cutting edge technology" means working on IE6 (exclusively, we aim to upgrade to IE7 at some point) so I feel I'm getting a little rusty on proper cutting edge stuff

https://developer.mozilla.org/en/Canvas_tutorial

http://docs.jquery.com

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
This is driving me batty. I have an element that is reporting the wrong offsetTop. Using either document.getElementById('myel').offsetTop and jQuery's jQuery('#myel').offest().top both give me 90 as the value... but I know for a fact that the element is at 97, since it's right up against something that's 97px tall that has no margin. In addition, Inspecting the element properties shows me offsetTop is, in fact 97.

:wtf:

Only registered members can see post attachments!

Lumpy fucked around with this message at 03:37 on Jul 22, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

epswing posted:

Can you duplicate this with a minimal example and post it?

I can duplicate it, but only on one machine... it's the damndest thing. On my Mac Mini, in Safari and Chrome, I see that ( even after a reboot, cache cleared, etc. ) My iMac and MBP, in both Safari and Chrome, as well as my XP machine with Chrome, FF and IE all report it correctly as 97.

I'm going to chalk it up to internet gremlins for now.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

sim posted:

I've got a similar, but more complicated question that involves offset. I'm trying to implement this: http://static.jqueryfordesigners.com/demo/fixedfloat.html into my design, but I'd like it to stay contained within a parent div so that it doesn't overlap the footer. I actually managed to do that by calculating the difference between the height of the fixed piece and the height of its container, then checking if position() + scrollTop() was greater than the difference.

That all works great. However now I need it to scroll back up, which means I need to find out if the scrollbar has moved past the height of the footer and my mind is sort of melting trying to figure out how to calculate that number since I can only get scrollTop() and not scrollBottom() like I wish I could. Here's the code:

code:
var top = $('#side').offset().top - parseFloat($('#side').css('marginTop').replace(/auto/, 0));

$(window).scroll(function (event) {
  // what the y position of the scroll is
  var y = $(this).scrollTop();
  
  var difference = $('#side').offsetParent().height() - $('#side').height();
  var topspace = $('#side').position().top;
		  
  // whether that's below the form
  if (y >= top) {
	// if so, ad the fixed class
	$('#side').addClass('fixed').removeClass('top');

	if(topspace + y >= difference){
		$('#side').removeClass('fixed').addClass('bottom');
	}
			
  } else {
  // otherwise remove it
        
        $('#side').removeClass('fixed').removeClass('bottom').addClass('top');
  }
	  
});

It would probably be easier to pass it the #footer and use that position().top + #side.outerHeight(true) as a limit.

I wrote a plugin that does that "pop out to fixed" a while back, and doing what you are trying to do, plus making sure if the thing you are floating is taller than the viewport it scrolls are on my TODO list. You have motivated me to finish!!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Finite posted:

I'm playing around with jQuery.

code:
$(document).ready(function()
{
	$(".checkbox input").bind("change", function() { return checkBoxToggle(this); });
}


function checkBoxToggle(e)
{
	var valueBox = $(e).siblings(".value");
	
	if ($(e).is(":checked"))
	{
		$(valueBox).removeClass("bad");
		$(valueBox).addClass("good");
		$(valueBox).text('Yes');
	}
	else
	{
		$(valueBox).removeClass("good");
		$(valueBox).addClass("bad");
		$(valueBox).text('No');
	}
	return false;
}
This code with some CSS builds something like this:



This works and is fine, but I'd like to run the code when the page loads as well as when the box is clicked, so it looks pretty from the beginning as opposed to just when you use it.

Is there a neat way to do this, another event I can tap into (and declare on the same line)? Or is it just a matter of manually calling checkBoxToggle() with a reference to the specific checkbox.

While that would be grand for one box, if I have 15 checkboxes and other fields with enhancements too, it's going to be a fair bit of clutter.

Before I get into your question proper, you should try not to perform the same selector over and over in your code. Your function should only call $(e) and $(valueBox) once. Speeds tings up a great deal. Also, siblings() already returns a jQuery wrapped object, so you don't need to re-wrap it.

As for the actual question:
code:
jQuery( function(){
  jQuery(".checkbox input").bind("change", function(){ 
   checkBoxToggle( jQuery(this) ); 
  }).each( function(){
    checkBoxToggle( jQuery(this) );
  });
});

function checkBoxToggle( jQe ){ // we now get a jQuery object
  var valueBox = jQe.siblings(".value");
  if ( jQe.is(":checked") ) {
    valueBox.removeClass("bad").addClass("good").text("Yes");
  } else {
    valueBox.removeClass("good").addClass("bad").text("No");
  }
}

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Rainbow Pony Deluxe posted:

Holy poo poo, dude, thank for the advice. jQuery makes Javascript into something resembling a sane programming language. It only took me a couple of minutes to do what I spent hours failing to do in Javascript. Cheers.


so I'm not really worried about it. If you could explain what's wrong with the original code, though, that'd be cool.

Javascript is a very sane programming language.

code:
eventList.innerHTML =ajax.responseText.split("\n");
You were trying to set the innerHTML of a DOM node to an Array object.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

OddObserver posted:

That actually works in general, due to Array.prototype.toString

So we should always assume we can use an array like a string?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

OddObserver posted:

I can't be anywhere that definitive; never thought it out. Except, well, in most contexts where it matters it will indeed auto-coerce into a string value (not to be confused with a string object, of course), e.g.: A = ["A", "B"]; A + "C"; produces "A,BC". And, well, most DOM methods will likely use the ToString operator as well, but those things always have wacko special cases.

JS might not be quite as sane as you might think. (See also valueOf).

And, well, obviously, stuff like index properties --- which aren't standard in 3rd edition anyway, dunno about 5th --- wouldn't use the string coercion, and neither would for .. in and the like.

See also auto-stringifying Selection object or whatever that was.

That was kind of my point. Telling beginners / people who are new to the language that assigning an Array literal where you want a string version of it as "generally OK thing" to do may not be in their best interests.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

NotHet posted:

AJAX question!
I am running into race conditions due to everything being asynchronous. How can I ensure I have my data before proceeding?
The following is my scenario!
code:
function ReadableFileFactory() {
	this.getReadableFile = function(path) {
		file = new ReadableFile();
		responseWritten = false;
		new Ajax.Request(path, {
			method: "post",
			onCreate: function(request) {
				request.transport.overrideMimeType('text/plain; charset=x-user-defined');
			},
			onSuccess: function(response) {
				file.setData(response.responseText);
			}
		});
		//file is being returned and acted on before the onSuccess of Ajax.Request is called
		return file;
	}
}
I could have getReadableFile accept a callback and pass my result to that... But I feel a little silly having to create a callback just to simply return an object. This gets super messy once I start needing to read multiple files. I'll have to write something to observe all of my file callbacks and run another callback when they are all executed.
This is turning into a gigantic mess very quickly just to ensure I have an object. Am I just approaching this from the wrong way? Is the callback-observer that I described the proper way to do things in javascript?

If you are just going to be spinning your wheels until you get your data, you might as well use a synchronous query (I'm using jQuery here because it's easy):

code:
file = new ReadableFile();
var data = jQuery.ajax({
  url: "someScript.php",
  async: false // <--- ooooh!
 }).responseText;
file.setData( data );

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

epswing posted:

But that will lock up the UI for as long as it takes to fetch the file, which could be half a second, but could also be two or three.

Yeah, so you show a "Loading data!" thing... I guess was assuming that locking the UI wasn't an issue because nothing could / should happen until data was loaded. Apparently, I assumed wrong!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:



and here is the xml file, saved as values.xml locally.

Any ideas what the problem might be?

1. Are you serving up the page via a web server, or file:/// url?

2. Why aren't you using jQuery? It makes life so much easier.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:

Sweet it works... in firefox. IE and google chrome still send the same errors but some searching around seems like chrome broke being able to look at local XMLs like this and I dont care about IE.

Oh well, when I get back to my linux box ill host something and mess with it there and Im gonna take a look into jQuery.

As Supervillin said, "stuff" is different when not served via http. Chrome actually decided to follow the correct way of doing things with file:/// URLs ( no cookies, etc. ) that "broke" many a thing that had been done using the up until that point "incorrect but everyone did it" way.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

skipdogg posted:

I'm creating a .pac file for our computers here at work, and we're rolling out a new proxy appliance that has an issue with a certain tool our agents use and I'm getting stuck trying to work around this.

I'm pretty sure whats happening is the site I'm trying to work around meets several of my if statements. How does one go about telling it to stop processing after an if condition is true. I know this is basic, but I have no idea about javascript or coding in general, and have only got this far learning as I go from sparse info about .pac files on google

So basically the if statements in the .pac are laid out like so (this is a very truncated version)

code:

function FindProxyForURL(url, host)
    {

if(
dnsDomainIs(host, "stupidsite.com")) {return old_proxy;}

if(
shExpMatch (url, "https://*.*.*.*") ||
shExpMatch (url, "https://*.*.*.*"))  
{return old_proxy;}

if(

isInNet(resolved_ip, "x.x.0.0", "255.255.0.0") ||  

(repeated about 40 times for 40 different subnets)
isInNet(resolved_ip, "x.x.0.0", "255.255.0.0"))
    {return no_proxy;}

{return new_proxy;}

}

I'm assuming the problem I have is the stupidsite.com URL also is a true condition for one of the isInNet statements as well. My question is, how can I make it so if the first or second if statements (dnsDomainIs or shExpMatch) it doesn't continue on to process all of the isInNet statements.

I'm guessing I might have to put some if / else if / else in there, but I'm at a loss to be honest.

Your code *should* work, since there is a return in every IF.

At least I think there is, but your crazy formatting makes it hard to tell.

The following behaves as expected: 'a' is matched, and the function returns, so the 'b' if statement doesn't run.

code:
var a = 2;
var b = 3;
function pie(){
 if( a == 2 ) {
   alert("hooray");
   return;
 }
 if( b == 3 ) {
   alert( "you won't see this" );
 }
}

pie();
EDIT: try formatting your code the Crockford Way(tm) and see if it works: you could be causing silent errors.

Lumpy fucked around with this message at 23:59 on Aug 12, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

emoltra posted:

Is there a way that I can replace one element with another? I'm writing a greasemonkey script and am trying to replace td elements with divs. I also need to preserve the class / ID attributes.

Uses jQuery, but does what you want, and gets all attributes:
code:
jQuery('td').each( function(){
  var i;
  var me = jQuery(this);
  var myAttrs = this.attributes;
  var newEl = jQuery('<div />');
  for( i = 0; i < myAttrs.length; i += 1 ){
    newEl.attr( myAttrs[i].name , myAttrs[i].value );
  }
  newEl.html( me.html() );
  me.replaceWith( newEl );
});

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mackerel, the Thief posted:

Brevity version:

code:
$('td').each(function() {
    for (i = 0, attrs = "", attrLength = this.attributes.length; i < attrLength; ++i)
        attrs += ' ' + this.attributes[i].name + '="' + this.attributes[i].value + '"';
    $(this).replaceWith( $("<div"+attrs+">"+$(this).html()+"</div>") );
});

You have a couple variable names to cut down one letter mister. He might be able to understand those parts.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mackerel, the Thief posted:

I really want to punch someone whenever I see something like this:

code:
$('td').each(function() {
    for (i = 0, t = this, a = "<div", b = t.attributes, l = b.length; i < l; ++i)
        a += ' ' + b[i].name + '="' + b[i].value + '"';
    $(t).replaceWith( $(a+">"+$(t).html()+"</div>") );
});

Can you come to where I work and start punching people? You've just written every piece of javascript, C, Java, and [ insert language here ] my "boss" writes. :(

EDIT: well, not quite, your code might work....

Lumpy fucked around with this message at 20:04 on Aug 24, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Tivac posted:

You probably want bases on those calls to parseInt or else if the input is something like "08" you aren't going to get the answer you want.

Always specify a base for calls to parseInt, seriously.

Yup. I had to fix a MAJOR BUG :supaburn: in a JS app last week... they had been trying to figure out what was causing the problem for three days. A user was passing '09' as a value to a function that used parseInt, and didn't do any bounds checking and passed of a value that never should have been more than 10 to something else that imploded (that also didn't do any input checking). I love working with people who literally say "well, javascript isn't a real language, so I'm not going to bother learning it; I just need to hack this out and I'll never have to use JS again." Despite having said that for the first time two years ago and having to work with JS more than any other language.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

HFX posted:

I could point to quite a few languages who do all the nice stuff Javascript does and better.

Great. Did anyone claim there weren't any?

For some topic related content, if you sometimes get stuck doing IE only apps like me, I just found out about this pretty awesome performance monitoring tool: http://ajax.dynatrace.com/pages/

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:

I want to be able to write to a json or xml file from a website using javascript. How would I go about doing something like this? I can open them and read just fine out of them using XMLHttpRequest, but is there a way to write?

Basically what I have is a gui for an application written in javascript using websockets which is then served up on individual webservers that users connect to to fire up this gui. There are a number of default values which I have to change in the javascript file itself to set but I would rather read from a json and have a button to write new defaults to this json if possible. Is what I am thinking of doing feasible?

You will have to send the modified json to the server for writing. This can be done with Ajax, but there will have to be some server side scripting for the actual file ( or database) write.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:

What if I stored to json file locally would that simplify things? Could I just read and write to it from within the javascript?

No, Javascript does not have any sort of file system access* due to it running inside the browser sandbox.

* you can use HTML5's localStorage to store data, but this is not filesystem access.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Golbez posted:

I can understand wanting to force a type with undefined, integers, floats, booleans, etc... but nothing coerced into a string will ever deliver the correct string. If you try to compare arg1 == "something", if arg1 is an int, there's no way it will ever == "something". It can only ever == "something" if it started out as a string in the first place. So in this case, it seems to me that using === for a non-blank string isn't necessary?

How does it hurt to use === instead of == ? And since === is actually faster than == , I guess the better question is why wouldn't you use ===?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Golbez posted:

My question was more along the lines of, why would geeves' coworker even need to do a 'typeof' in this case? The only possible type that can ever == "something" is a string. It's not like == "1", where a string or int could work.

I'm slowly moving towards using ===s, though since most of my work is in PHP, and form submissions are always strings, that can sometimes be a little counterintuitive.

Ah, sorry, I misunderstood your point. Yeah, the typeof is pointless in that case. but

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Gentle Marmot posted:

Sorry this is just frustrating.

I need to get the text out of a certain cell in my table. Then what I want to do is check that text against something and delete the row its found in. Like I said the farthest ive gotten is making a list of all the rows.

Use jQuery.

code:
jQuery( '#yourTableID td' ).each( function(){
  var theTD = jQuery(this);
  var blah = theTD.val(); // the TD's text
  if( blah === 'some string' ) {
    theTD.parent().remove();
    // return if you know you will only find it once.
  }
});

Lumpy fucked around with this message at 19:26 on Sep 29, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

chippy posted:

I have a page that is working perfectly in Chrome and Firefox, but IE7 a couple of lines are causing errors. Unfortunately the only error message give is the extremely unhelpful "Object expected" and I don't trust the line numbers it's giving me (one of them seems to be referring to a <TR> tag in a table and not actually a script at all).

I have to get this working on IE as some of our lab machines only have that installed and we can't put another browser on, so:

- Has anyone encountered this error and know what it means? From googling it kind of seems like a generic error thrown out by IE in a lot of different situations that doesn't actually tell us much.

- Can anyone recommend a good javascript debugging tool for use with Internet Explorer?

The code itself is pretty trivial, one function populates a text box with the current date, formatted a certain way and is called on the page loading, another simple popualtes a text box when it gains focus with values from a couple of other text boxes and a multi-select. I don't even know where to start debugging it since it's working fine in the other two browsers. I'm not even sure if it's my function that's screwing things up, I actually think it might be some code further up the page which I didn't write which is bugging out IE and causing the rest of the scripts not to run properly.

You can try FireBug Lite or IE Developer Toolbar

If you post a link to your code, I'm guessing somebody will be able to quickly see what the problem is.

EDIT: If you can, test in IE8 and see if the problem happens there: IE8 actually has a not terrible built in console / debugger.

Lumpy fucked around with this message at 13:33 on Oct 1, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

chippy posted:

OK, if anyone's interested in helping, pastebin of the entire page is here: http://pastebin.com/YcCypnPG

The lines causing issues according to IE are:

Syntax error enter_bug.cgi?product=CS77V1, line 285 character 3
Object expected enter_bug.cgi?product=CS77V1, line 134 character 1
Object expected enter_bug.cgi?product=CS77V1, line 834 character 1
Object expected enter_bug.cgi?product=CS77V1, line 834 character 1

If anyone can shed any light I'd be really grateful, I'm pretty much getting nowhere here.

Couple quick things to try:

1. You define the set_assign_to() fuction AFTER the body tag... IE might not like that (although it shouldn't be a problem... but this is IE)

2. On line 285, you call this:

code:
TUI_hide_default('expert_fields');
And I see that 'expert_fields' is a classname you give to elements later on in the DOM. Is that TUI_hide_default() function attempting to find DOM nodes with that class before they exist and crapping out?

There is a lot of "less than best practices" code in there.

code:
var initialowners = new Array(1);
var last_initialowner;
var initialccs = new Array(1);
var components = new Array(1);
var comp_desc = new Array(1);
var flags = new Array(1);
    components[0] = "unspecified";
    comp_desc[0] = "unspecified";
    initialowners[0] = "ben.abbott\x40nokia.com";
    flags[0] = [1];
 
    initialccs[0] = "";
should be

code:
var initialowners = ['ben.abbott\x40nokia.com'];
var components = ['unspecified'];
// etc...
99.9999999998% of the time, don't use new Array() or new Object(), use literal notation instead.

Lumpy fucked around with this message at 16:30 on Oct 1, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

chippy posted:

Well gently caress a duck, I just had to move the "-->" to the end of the script block instead of half way through it. Retard :)

Do yourself a favor and remove those comment things completely. Unless you are supporting Mosaic 0.96, you don't need them.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

ATLbeer posted:

So, I'm trying to learn JavaScript objects and making a reusable RSS FeedObject (don't worry about x-browser compatibility)

code:
function FeedObject(name, url){
        this.name = name;
        this.url = url;
        this.items = new Array();
        this.ro = new XMLHttpRequest();
        this.feed_fetched = function(){
            if (this.ro.readyState==4){ //feed fetched correctly
                console.log(this.ro)
            }//readyState
        }//feed_fetched
        this.populate_feed = function(){
            this.ro.open("GET", this.url, true); 
            this.ro.onreadystatechange = this.feed_fetched;
            this.ro.send();
        }//populate_feed        
    }//FeedObject
gently caress.... the caller to feed_fetched is XMLHTTPRequest not the parent... So the XMLHTTPRequest object is 'this' not the 'parent'...

umm.. .Ok, so how do I reference items, if this is now something else.?

Don't bother with new or this at all.....

code:
function feedObject( name, url ) {
 var items = [];
 var ro = new XMLHttpRequest();
 var feed_fetched = function(){
   window.console.log(ro);
   if (ro.readyState == 4){ //feed fetched correctly
      window.console.log("fetched")
   }//end readState
 };
 var self = {
   populate_feed: function(){
        ro.open("GET", url, true); 
        ro.onreadystatechange = feed_fetched;
        ro.send();
   }
 }
 return self;
}

var feedOne = feedObject( 'a', 'http://w.com' );
feedOne.populate_feed(); // hooray!
If you want to learn JS objects and so on, read Crockford's java script: The Good Parts

Lumpy fucked around with this message at 14:01 on Oct 8, 2010

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

dark_panda posted:

[Good stuff about 'this' and constructors]

And that's why I don't bother with prototypical constructors and new. That said, that is an excellent little write-up panda, you should post it somewhere.

dark_panda posted:

I highly recommend his video series on JavaScript on YUI Theatre, as they're well worth watching. They're the sort of videos where, yeah, they're focused on JavaScript, but he packs so much history of our industry into the videos that they could have well been about BASIC and been just as interesting.

http://developer.yahoo.com/yui/theater/


These are must-watches for anyone doing JS, and like you said, a really cool history even if you don't.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

wins32767 posted:

I need a visualization/graphing JS library. Any suggestions?

Flot: http://code.google.com/p/flot/

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

DholmbladRU posted:

i am not sure if this is a Js question or html.

I have a text box that a user will be typing a currency value into it. I would like a comma to be inserted while the user is typing if they go over a a thousand, and a period where decimals are applicable.

Here is an example of the input box so far.
<input type="text" value="0.0"onblur="if (this.value=='') this.value='0.0';" onfocus="if (this.value==this.defaultValue) this.value='';" name="YearMisc" />

It's a javascript question. You want to attach a keyup event to the input, and every time they enter something, pass the value through a regex that removes all non-digits, then adds commas in the right places, and sets the form input to that new string.

Tivac posted:

code:
var select = document.getElementById("my_select");

var item = select.options[select.selectedIndex].value;

code:
jQuery('#my_select').val();
:v:

Lumpy fucked around with this message at 01:11 on Oct 20, 2010

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