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
KuruMonkey
Jul 23, 2004

Master_Odin posted:

What weird functionality as it appears to work perfectly after I refreshed the page a couple times, even though at first it did allow the "Getting Started" page to go through while nothing else.

I think what's interesting is that reload() works, but assigning the location did not.

Adbot
ADBOT LOVES YOU

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug
I had an idea for an app to make my work life a little easier and to work on some HTML 5 skills. The app would be for creating and maintaining a list of records and having some default (but configurable) settings seeded for new records to use. Because of the deployment scenarios I'm really hoping to keep this pure HTML 5 and JavaScript. Deployment will require that the data stored by the app be transferable along with a copy of the app. Example: If someone copies the entire folder the app runs out of to a thumb drive then the a copy of the data should go right along with it. This means HTML 5 local storage is immediately disqualified as an option.

My next thoughts were XML and JSON. Googling has turned up a few techniques and libraries for either reading or writing XML using JavaScript. I'd prefer to keep my dependencies down to one library if possible. I haven't been able to find much on reading/writing JSON to files. Does anyone have any preferred or recommended libraries for either of these formats? I'm curious to find out how others have approached similar scenarios and what lessons and pitfalls reside along the way.

NotShadowStar
Sep 20, 2000
Sounds like Sproutcore but Sproutcore

-is kind of difficult to learn
-is going through some flux at the moment
-can't write back to local files

You're always going to have problems with the last. Javascript can't read/write files from the browser for a good loving reason.

You can serialize read only data with Sproutcore though if that's all you need. In fact the getting started introduction uses a static object.

But, Sproutcore is kind of difficult to learn, especially if you don't have any experience with OSX or iPhone type development. It follows the same development patterns since it was largely an Apple project.

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug
After thinking about it more I suppose the best approach is to just display/receive a pop up with a data dump if a user needs to transfer records.

N.Z.'s Champion
Jun 8, 2003

Yam Slacker
You can use something like store.js as a wrapper around localStorage and cookies.

Vat of Lead
Sep 21, 2008

5/8/09 Never Forget
I'm following along in a textbook and it told me to run a function like this:
code:
<body onload=NYClock()>
The function puts text into several form fields on the page.
This works just fine in Chrome, but not in Firefox 4. Is this normal?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Vat of Lead posted:

I'm following along in a textbook and it told me to run a function like this:
code:
<body onload=NYClock()>
The function puts text into several form fields on the page.
This works just fine in Chrome, but not in Firefox 4. Is this normal?

Yes.

code:
<body onload="NYClock();">
Would be the 'correct' way to do it. Actually, the really, really correct way is to assign a callback function to the onload event in your script somewhere, but if you are just starting out, you'll get to that later.

Adahn the nameless
Jul 12, 2006
I'm interested in learning javascript from some ASP.NET stuff I want to do. Does anyone have a recommended introduction site or something along those lines?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Adahn the nameless posted:

I'm interested in learning javascript from some ASP.NET stuff I want to do. Does anyone have a recommended introduction site or something along those lines?

http://javascript.crockford.com/

Buy his book "java script: The Good Parts" as well. The mozilla docs are a good reference as well: https://developer.mozilla.org/en/JavaScript/Reference

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

Adahn the nameless posted:

I'm interested in learning javascript from some ASP.NET stuff I want to do. Does anyone have a recommended introduction site or something along those lines?

http://eloquentjavascript.net/

Also seconding the recommendation for Crockford's book, just go into it knowing that he is VERY opinionated & you don't have to agree with everything he says.

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies
How would I submit a form inside an iframe? The form is set-up correctly that outside the iframe, it submits fine and what have you. However, when trying to do:
code:
document.getElementById('evilFrame').contentWindow.document.getElementById('evil').submit();
I've tried some variations, but kept just getting that this equals null and so .submit() fails.

The ids are right with the first being the frame and the second being the form.

geeves
Sep 16, 2004

Master_Odin posted:

How would I submit a form inside an iframe? The form is set-up correctly that outside the iframe, it submits fine and what have you. However, when trying to do:
code:
document.getElementById('evilFrame').contentWindow.document.getElementById('evil').submit();
I've tried some variations, but kept just getting that this equals null and so .submit() fails.

The ids are right with the first being the frame and the second being the form.

Try something like this with jQuery:

code:
$("#iFrame").contents().find("#someForm").submit();
Before the .submit() is how to access elements in an iFrame (just note you're subject to the same origin policy.

http://forum.jquery.com/topic/jquery-how-to-access-iframe-window

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies
It's a CSRF lab so I don't think the policy is overly important?

Basically, I'm just trying to come up with a way to make it so that when I submit a form to the "vulnerable" website, I'm supposed to be able to edit their profile/make a new post/etc. However, when submitting a POST form with the .submit() command, I get sent to the site which would be no good for trying to silently mess with people. Tried to use an iFrame to just load the form in it and send it through that but it still doesn't seem to work (not getting an error anymore on the script though so thanks for that).

It's annoying as basically our professor gave us this lab document obviously gotten from elsewhere and we're expected to teach ourselves javascript and html to perform these things and ugh.

My code is:
code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
window.onload = function() {
   $("#evilFrame").contents().find("#evilFrame").submit();
}
</script>
<body>
<iframe name='evilFrame'>
<form action='http://www.someothersite.com/' method='POST'>
<!-- inputs here -->
</form>
</iframe>
</body>
it works if I remove the iframe, but like I said, it just redirects the entire page (to a completed form redirect) which I feel isn't exactly what I'm looking for.

Sub Par
Jul 18, 2001


Dinosaur Gum
I have a complete idiot question. I am not a web developer, and I do not have much control over the product I'm using. I work at a nonprofit doing database things, and me and my small team are the only computer-literate people here so this problem was dumped on us to solve and we have about 2 hours.

I have a page. It is the second step of a two-step process for signing up for our email list. Step one: fill out a form. Step two, a confirmation page is displayed that has a <form> tag, inside of which is a <table> that displays everything you entered in step 1. After the table ends, there are a bunch of <inputs> that are hidden that store the actual data that you entered in step 1.

I would like to hide a couple of the rows in this table using javascript, but can't seem to make it work. The gist of what I want to do is:
code:
<script language="javascript" type="text/javascript">
document.getElementById('inputfieldcellPHONE').style.display = 'none';
</script>
It's not letting me do that, and it appears it's because I'm just not accessing the DOM correctly. But I can't figure out how to do this correctly for the life of me. Any thoughts? Thanks.

edit: here's the source for the page showing that I am, I believe, getting the right element
code:
<td class='inputcaptioncell' id='inputcaptioncellPHONE'>Phone Number:</td>
<td class='inputfieldcell' id='inputfieldcellPHONE'>222-333-4444</td>
I just want it to say "Phone Number:" and then nothing. Not "Phone Number: 222-333-4444".

Sub Par fucked around with this message at 21:51 on Apr 14, 2011

Munkeymon
Aug 14, 2003

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



If that's all you want to do, just set the innerHtml property to an empty string (or a space if the empty fucks up somehow): document.getElementById('inputfieldcellPHONE').innerHtml = '&nbsp;';

Sub Par
Jul 18, 2001


Dinosaur Gum

Munkeymon posted:

If that's all you want to do, just set the innerHtml property to an empty string (or a space if the empty fucks up somehow): document.getElementById('inputfieldcellPHONE').innerHtml = '&nbsp;';

I tried that. I can't get it to manipulate the DOM for these parts of the page at all. When I try
code:
alert(document.getElementById('inputfieldcellPHONE').innerHtml);
No alert comes when the page loads.

Munkeymon
Aug 14, 2003

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



Are you sure you're doing this when the DOM is loaded? If you just stick it in a bare script node in the header, it will run before the browser is ready to manipulate the HTML.

Sub Par
Jul 18, 2001


Dinosaur Gum

Munkeymon posted:

Are you sure you're doing this when the DOM is loaded? If you just stick it in a bare script node in the header, it will run before the browser is ready to manipulate the HTML.

Good call. I can't really control much about where it goes, but it does remind me that when I tried running just alert("Blah");, I got the alert while the table itself hadn't yet loaded. Thanks. I'll try something else.

Munkeymon
Aug 14, 2003

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



http://www.webreference.com/programming/javascript/onloads/ might help with the onload thing

There Will Be Penalty
May 18, 2002

Makes a great pet!
It's innerHTML, not innerHtml.

Just about everything is case-sensitive here.

Also, this statement

code:
document.getElementById('inputfieldcellPHONE').style.display = 'none';
will *only* work if the <script> element it's in is somewhere after the <td> in question (like just before the closing </body> tag), or that statement is in an onload handler like what Munkeymon said.

EDIT: but when you start thinking about onload handlers and poo poo, I'd say gently caress it and use jQuery.

Adahn the nameless
Jul 12, 2006
Thanks for the recommendations for Crockford's book and the Mozilla references. Any recommendations for jquery in particular? Besides skimming the docs and fooling around with the API, of course.

edit: Hah, didn't even see the jquery thread. I'll look there.

uG
Apr 23, 2003

by Ralp
So i'm trying to create an edit user form that uses jQuery. First there is a list of users, with an Edit link to the side. If you click edit, the link and the selected name is replaced with an input box to change the user's name, and a submit button.

My problem seems to be that since the form for the input box isn't rendered when the page is first created, my javascript that i've c&p'd below isn't getting hooked (at least I think that is the problem).

code:
    <script type="text/javascript">
	;(function ($) {
		// Passing in a function is the same as passing it into $(document).ready()
		$(function () {

			// Find the form
			$("#user-edit form")
				// Hook into the "on-submit" handler.  Inside this function, "this"
				// refers to the form element.
				.submit(function () {

					function _handleSuccess (data, textStatus, XMLHttpRequest) {
						// ...
					}

					function _handleError (XMLHttpRequest, textStauts, errorThrown) {
						// ...
					}

					$.ajax({
						url:  $(this).attr("action")
					, type: "PUT"
					, data: $(this).serialize()
					, dataType: "json"
					,	success:	_handleSuccess
					,	error:    _handleError
					})
				})
		})
	})
    </script>
So how am I supposed to hook into forms that are created dynamically and returned from an ajax get?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

uG posted:

So i'm trying to create an edit user form that uses jQuery. First there is a list of users, with an Edit link to the side. If you click edit, the link and the selected name is replaced with an input box to change the user's name, and a submit button.

My problem seems to be that since the form for the input box isn't rendered when the page is first created, my javascript that i've c&p'd below isn't getting hooked (at least I think that is the problem).

code:
    <script type="text/javascript">
	// code
    </script>
So how am I supposed to hook into forms that are created dynamically and returned from an ajax get?

There are many things wrong with this code, but the #1 is that it will NEVER RUN.

Let's remove the complicated stuff inside your outer function and put in something simple as a test:

code:
(function ($) {
  alert("Hey, this code ran!");
});
Now reload your page. No alert. Your code is never run because nothing ever calls that function. You can make it call itself, but you don't want to do that; you want something to happen when your form is submitted, and to do that you have to use some of the stuff that's in your code, namely waiting for the DOM to load, then attaching to the form's SUBMIT handler:

code:

jQuery(function () {  // when the DOM loads, run this function
  
  jQuery('#myFormId').submit(function () { // when my form is submitted, run this function

     // code to execute when form is submitted
  });

});

Lumpy fucked around with this message at 04:02 on Apr 18, 2011

uG
Apr 23, 2003

by Ralp

Lumpy posted:

There are many things wrong with this code, but the #1 is that it will NEVER RUN.

Let's remove the complicated stuff inside your outer function and put in something simple as a test:

code:
(function ($) {
  alert("Hey, this code ran!");
});
Now reload your page. No alert. Your code is never run because nothing ever calls that function. You can make it call itself, but you don't want to do that; you want something to happen when your form is submitted, and to do that you have to use some of the stuff that's in your code, namely waiting for the DOM to load, then attaching to the form's SUBMIT handler:

code:

jQuery(function () {  // when the DOM loads, run this function
  
  jQuery('#myFormId').submit(function () { // when my form is submitted, run this function

     // code to execute when form is submitted
  });

});

I'm getting the html for the form from an ajax request, so it doesn't exist until after $(document).ready. How is the javascript that loads with the original page supposed to know when my new form suddenly appears? Do I need to tie into the javascript that makes the ajax get call that gets the form html?

I'm assuming that is the problem, as the code you posted doesn't seem to be catching the submit either. It's my first day with javascript, so forgive me if I am missing something you already said.

MonkeyMaker
May 22, 2006

What's your poison, sir?

uG posted:

I'm getting the html for the form from an ajax request, so it doesn't exist until after $(document).ready. How is the javascript that loads with the original page supposed to know when my new form suddenly appears? Do I need to tie into the javascript that makes the ajax get call that gets the form html?

I'm assuming that is the problem, as the code you posted doesn't seem to be catching the submit either. It's my first day with javascript, so forgive me if I am missing something you already said.

code:
$("#myFormId").live('submit', function() {
    // whatever
});
That'll execute on submit of any form with that ID. Obviously, to be really useful, you want classes instead of IDs.

uG
Apr 23, 2003

by Ralp
Ok I cleaned up the code like you said Lumpy. I have:

code:
    <script type="text/javascript">
	;(function ($) {
		$(document).ready(function () {
			$("form").ajaxForm({
				beforeSubmit: function () { /* validate */ }
			,	success:      function () { /* notify success */ }
			})

		})

	})(jQuery)
   </script>
This works with a form that loads with the page. But it doesn't work with the same form that is retrieved and inserted with ajax (user clicks a hyperlink and the form appears). I tried changing $(document).ready to $("form").live, but that just breaks it, as does adding a $("form").live('submit' function() { alert("TEST")}) function to see if it is catching the event.

uG fucked around with this message at 02:19 on Apr 20, 2011

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

uG posted:

Ok I cleaned up the code like you said Lumpy. I have:

code:
    <script type="text/javascript">
	;(function ($) {
		$(document).ready(function () {
			$("form").ajaxForm({
				beforeSubmit: function () { /* validate */ }
			,	success:      function () { /* notify success */ }
			})

		})

	})(jQuery)
   </script>
This works with a form that loads with the page. But it doesn't work with the same form that is retrieved and inserted with ajax (user clicks a hyperlink and the form appears). I tried changing $(document).ready to $("form").live, but that just breaks it, as does adding a $("form").live('submit' function() { alert("TEST")}) function to see if it is catching the event.

You still have all sorts of extra crap all over the place.

What is that leading semi-colon? Why do you wrap it all in a self-calling function? :iiam:

code:
<script>
jQuery(function () {
  jQuery('#someId').live('submit', function(event) {
     //client side validation goes here
     //
     var formData = jQuery(this).serialize();
     jQuery.post(
        'someURL.php',
         formData,
         function (data) {   // this is the success function
            // do stuff with the return data if you need to
     });
     return false;  // otherwise your form wil submit normally.
  });
});
</script>
EDIT: that code is ALL you need... don't put it inside anything else, and if you got the idea to do that crazy wrapping from a tutorial or somebody else, don't read that / listen to them any more.

Lumpy fucked around with this message at 03:56 on Apr 20, 2011

uG
Apr 23, 2003

by Ralp

Lumpy posted:

You still have all sorts of extra crap all over the place.

What is that leading semi-colon? Why do you wrap it all in a self-calling function? :iiam:

code:
<script>
jQuery(function () {
  jQuery('#someId').live('submit', function(event) {
     //client side validation goes here
     //
     var formData = jQuery(this).serialize();
     jQuery.post(
        'someURL.php',
         formData,
         function (data) {   // this is the success function
            // do stuff with the return data if you need to
     });
     return false;  // otherwise your form wil submit normally.
  });
});
</script>
EDIT: that code is ALL you need... don't put it inside anything else, and if you got the idea to do that crazy wrapping from a tutorial or somebody else, don't read that / listen to them any more.
Yea I got that from a tutorial. Thanks for the code. I removed the var formData and jQuery.post and used ajaxForm instead since the server wasn't receiving any data. Needless to say as much as this simple problem drove me bonkers, i'm starting to like javascript again.

KingEup
Nov 18, 2004
I am a REAL ADDICT
(to threadshitting)


Please ask me for my google inspired wisdom on shit I know nothing about. Actually, you don't even have to ask.
Hey I needs some help. I've been using this greasemonkey userscript for years:

code:
// ==UserScript==
// @name           pls
// @namespace      [url]http://er0k.org/tmp/[/url]
// @include        *
// ==/UserScript==

(function() {

  function addStyles(css) {

      var head, style;
      head = document.getElementsByTagName('head')[0];
      if (!head) { return; }
      style = document.createElement('style');
      style.type = 'text/css';

      style.innerHTML = css;
      head.appendChild(style);
  }
  
  var i, href, pls, div, img;
  
  // MP3s or M4As
  var xpath = '//a[contains(@href, "mp3")] | //a[contains(@href, "m4a")]';

  var mp3s  = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  
  var links = new Array();
  for (i = 0; i < mp3s.snapshotLength; i += 1) {
      href = "File" + i + "=" + mp3s.snapshotItem(i).href;

      if (href.match(/\.mp3$/) || href.match(/\.m4a$/)) { links.push(href.replace(/%20/g, "%2520")); }
  }
  pls = links.join('%0A'); // newline
  if(!pls) { return; }
  img = 
      '<img src="data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%0C%00%00%00%0C%08%00'  +

      '%00%00%00s%1E%03%3B%00%00%00%02bKGD%00%FF%87%8F%CC%BF%00%00%00%09pHYs%00%00%0B%13%00%00%0B' +
      '%13%01%00%9A%9C%18%00%00%00%07tIME%07%D5%06%07%06%2F%0Em%99%83%FD%00%00%00sIDATx%DAM%CC%AD' +

      '%0A%C2%60%00F%E1%E7%9B%DF%FCc%0B%06%B3W%25%88%C5%A0A%D0%AB1Y%0C%16%8B7%25%08%C6%05%C3d%0A'  +
      '%D3%E0d%9E%F2r8%F0%86BK%F2%9D%ED%9F%CC%DE%AD%AC%07%15s%A2E%B7%AE%D3%17%A7%E5!%CA%C3%B3%EA'  +

      '%F5%91K%94%E5cpIq%95%C8%3A%D9%7Dr%C3X%B4c%15Gl%F6B%01%D3%E1%F1w%1D%9C3hJ%C3%07h%02%182%E1k' +
      '%AB%AC%00%00%00%00IEND%AEB%60%82">';
  div = document.createElement('div');

  div.id = 'gm-playlist';
  div.innerHTML = '<a href="data:audio/x-scpls,' + encodeURIComponent('[playlist]\nNumberOfEntries=') + (mp3s.snapshotLength - 1) + encodeURIComponent('\n') + pls + encodeURIComponent('\n') + 'Version=2">' + img + '</a>';


  // (onload caused problems - not needed)å
  if(pls) {
    document.body.appendChild(div);
  }

  addStyles(
  '#gm-playlist div, #gm-playlist a,' +
  '#gm-playlist a:hover, #gm-playlist a:link {' +

  '   margin: 0;' +
  '   padding: 0;' +
  '   border: 0;' +
  '   text-decoration: none;' +
  '}' +
  '#gm-playlist img {' +
  '   position: fixed;' +

  '   z-index: 99999;' +
  '   top: 15px;' +
  '   right: 15px;' +
  '   margin: 5px;' +
  '   padding: 5px;' +
  '   color: #000;' +
  '   background-color: #eee;' +

  '   border: #000 1px solid;' +
  '}'
  );

})();
However it's not working properly with a the newer version of Firefox. The problem appears [I think] to be a bug in the way Firefox 4 handles files with special characters in them or no filename at all:

https://bugzilla.mozilla.org/show_bug.cgi?id=622400
https://bugzilla.mozilla.org/show_bug.cgi?id=475008

I end up with weird file names like this:



All I want is a filename that looks like this 'diFhdXo.pls' (without the 'pls-1.part' bit)

I was hoping someone knew how to modify the js so it creates filenames without the offending characters in them.

KingEup fucked around with this message at 07:37 on Apr 22, 2011

ZippySLC
Jun 3, 2002


~what is art, baby dont post, dont post, no more~

no seriously don't post
I have a bit of Javascript on my website that grabs a random image and uses it for a banner:

code:

<script language="JavaScript">
imgswap = new Array(

'<div class="nav-random" style="background: url([url]http://common.njpinebarrens.com/images/header/header-001.jpg[/url]); background-position: right; background-repeat: no-repeat;"></div>',
...
'<div class="nav-random" style="background: url([url]http://common.njpinebarrens.com/images/header/header-094.jpg[/url]); background-position: right; background-repeat: no-repeat;"></div>');

rnd.today=new Date();
rnd.seed=rnd.today.getTime();

function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};

function rand(number) {
return Math.ceil(rnd()*number);
};
Can someone suggest me a way that I can just have it look at whatever images are in the header directory and use one, rather than explicitly specifying filenames in the code?

I should say that I am not a Javascript programmer and that this is someone elses code example that I used and have outgrown.

epswing
Nov 4, 2003

Soiled Meat

ZippySLC posted:

the header directory

The what?

MonkeyMaker
May 22, 2006

What's your poison, sir?

ZippySLC posted:

I have a bit of Javascript on my website that grabs a random image and uses it for a banner:

code:
javascript...
Can someone suggest me a way that I can just have it look at whatever images are in the header directory and use one, rather than explicitly specifying filenames in the code?

I should say that I am not a Javascript programmer and that this is someone elses code example that I used and have outgrown.

Javascript can't access the filesystem (as best I know). You could have some sort of PHP/etc script that provides a list of files, grab that through AJAX and then select an image from that list.

subx
Jan 12, 2003

If we hit that bullseye, the rest of the dominoes should fall like a house of cards. Checkmate.
If all the files are named sequentially anyways, can't you just do a random and then append that to the filename? Not sure why you'd need to make the array in the first place.

ZippySLC
Jun 3, 2002


~what is art, baby dont post, dont post, no more~

no seriously don't post

epswing posted:

The what?

The directory where all of the header images are located.

subx posted:

If all the files are named sequentially anyways, can't you just do a random and then append that to the filename? Not sure why you'd need to make the array in the first place.

Can you give me a bit of example code? :)

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

ZippySLC posted:

I have a bit of Javascript on my website that grabs a random image and uses it for a banner:

code:

<script language="JavaScript">
imgswap = new Array(

'<div class="nav-random" style="background: url([url]http://common.njpinebarrens.com/images/header/header-001.jpg[/url]); background-position: right; background-repeat: no-repeat;"></div>',
...
'<div class="nav-random" style="background: url([url]http://common.njpinebarrens.com/images/header/header-094.jpg[/url]); background-position: right; background-repeat: no-repeat;"></div>');

rnd.today=new Date();
rnd.seed=rnd.today.getTime();

function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};

function rand(number) {
return Math.ceil(rnd()*number);
};
Can someone suggest me a way that I can just have it look at whatever images are in the header directory and use one, rather than explicitly specifying filenames in the code?

I should say that I am not a Javascript programmer and that this is someone elses code example that I used and have outgrown.

You realize that javascript has a built in Math.random, right? No need to roll your own.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random

Also if you want to write an array literal, instead of
code:
var imgswap = new Array (1,2,3);
you can just do
code:
var imgswap = [1,2,3];

ZippySLC posted:

Can you give me a bit of example code? :)
Assuming you have filenames of the form: 'header-XXX.jpg'
where XXX is a number from 001 to some maxFilenumber:
code:
var maxFileNumber = 100;
var fileNumber = Math.ceil(Math.random() * maxFileNumber);
var numStr = ("00" + fileNumber).slice (-3);
doStuff('<div class="nav-random" style="background: url([url]http://common.njpinebarrens.com/images/header/header-' + filenumber + '.jpg[/url]); background-position: right; background-repeat: no-repeat;"></div>');

Winkle-Daddy
Mar 10, 2007
Bah, I have avoided learning JS for years now, and I have decided to not put it off any longer!

I'm having trouble with my very first test here. This is what I've got:

code:
<html>
<head>
<script type="text/javascript">
	function checkAdopt(feature)
	{
		alert(feature);
		document.formName.feature.checked=true;
	}
</script>
</head>
<body>

	<input type="button" value="test" onClick="checkAdopt('blue');" />	
	<br /><br /><br />
	<form name="formName">
		<input type="checkbox" name="blue" value="blue" />Blue<br />
		<input type="checkbox" name="red" value="red" />Red<br />
		<input type="checkbox" name="green" value="green" />Green<br />
	</form>
</body>		
</html>
It should be pretty self evident that all I'm trying to do is modify the check box next to "blue" from not checked to checked when the button is clicked.

If I hard code the second line in the function to read:
code:
document.formName.blue.checked=true;
Then it works just fine.

How the hell do I do this?

edit: Oooh, getElementById is much better.

Winkle-Daddy fucked around with this message at 22:42 on May 11, 2011

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Winkle-Daddy posted:

code:
document.formName.feature.checked=true;

code:
document.formName[feature].checked=true;
In yours, it's looking for something named "feature".

Winkle-Daddy
Mar 10, 2007

FeloniousDrunk posted:

code:
document.formName[feature].checked=true;
In yours, it's looking for something named "feature".

Thanks! That's what I was looking for but wasn't sure how to phrase it in a google friendly way.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
This is confusing me.

console.log(oVar[i]) = [ "XXNULLXX" ].

console.log(oVar[i] === 'XXNULLXX') = false.

console.log(oVar[i] == 'XXNULLXX') = true.

I don't think I've ever seen a situation where a == on a string vs. string can return true but === returns false. Can someone please explain this?

Edit: It appears that for some reason it's being double-object wrapped: oVar is [ [ "XXNULLXX" ] ]. So really, I'm saying "object == 'XXNULLXX'", and I'm sure through some weird casting that's coming out to true.

Golbez fucked around with this message at 16:42 on Jun 7, 2011

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Golbez posted:

This is confusing me.

console.log(oVar[i]) = [ "XXNULLXX" ].

console.log(oVar[i] === 'XXNULLXX') = false.

console.log(oVar[i] == 'XXNULLXX') = true.

I don't think I've ever seen a situation where a == on a string vs. string can return true but === returns false. Can someone please explain this?

Edit: It appears that for some reason it's being double-object wrapped: oVar is [ [ "XXNULLXX" ] ]. So really, I'm saying "object == 'XXNULLXX'", and I'm sure through some weird casting that's coming out to true.

if it's really [["XXNULLXX"]] then it's an array being compared to a string... and the array has it's .toString called to try to cast it so it can compare when you do the double equals check. Since there's only one element in the array, that returns the single element as a string matching what you are looking for, and it returns true.

Fun example:

code:
['one','two','three'].toString(); // "one,two,three"
['one','two','three'] == "one,two,three" // true

Lumpy fucked around with this message at 01:40 on Jun 8, 2011

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