KevinM1
Moderators-
Posts
5,222 -
Joined
-
Last visited
-
Days Won
26
Everything posted by KevinM1
-
I haven't tried this myself, but try: var formField = createElementNS("http://www.w3.org/1999/xhtml", "input"); formField.setAttribute("size", "4"); formField.setAttribute("name", "text1"); formField.setAttribute("id", "text1"); formField.setAttribute("type", "text");
-
Okay, first, from the looks of things, you probably have a submit element that's something along the lines of: <input type="submit" name="submit" value="submit" onclick="this.calculate();" /> If so, you'll need to remove the onlick or anything referencing JavaScript from it. Now, to the script itself: <script type="text/javascript"> /* Note how there's no HTML comments (i.e., <!-- -->). All modern browsers understand JavaScript, so adding them is pointless. We're going to keep the image caching and swapping functions. I'm not going to re-write them in my coding style, but just be aware that my style is different than the style these initial functions use. I'm just mentioning it because you're a self-proclaimed newbie, so I don't want to throw you off. */ function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } var myForm = document.forms["form2"]; //obtain a reference to the form var myFormInputs = myForm.elements; //obtain a reference to all of the inputs in the form itself myForm.onsubmit = calculate; //set the form to run the calculate() function when a user attempts to submit information function calculate() { var validKids = false; var validAdults = false; if(!parseInt(myFormInputs["NUMBER-OF-KIDS"].value, 10) > 0) { var numKids = 0; } else { var numKids = myFormInputs["NUMBER-OF-KIDS"].value; } if(!parseInt(myFormInputs["NUMBER-OF-SPECIAL-NEEDS"].value, 10) > 0) { var numSpecNeeds = 0; } else { var numSpecNeeds = myFormInputs["NUMBER-OF-SPECIAL-NEEDS"].value; } if(!parseInt(myFormInputs["NUMBER-OF-CARERS"].value, 10) > 0) { var numCarers = 0; } else { var numCarers = myFormInputs["NUMBER-OF-CARERS"].value; } if(!parseInt(myFormInputs["NO-OF-S-CITIZENS"].value, 10) > 0) { var numSeniors = 0; } else { var numSeniors = myFormInputs["NO-OF-S-CITIZENS"].value; } if(!parseInt(myFormInputs["NO-OF-ADULTS"].value, 10) > 0) { var numAdults = 0; } else { var numAdults = myFormInputs["NO-OF-ADULTS"].value; } if((numKids + numSpecNeeds + numCarers + numSeniors + numAdults) < 15) //if there are fewer than 15 people { alert("At least 15 people must sign up!"); //alert the user of the error return false; //stop submission } else //else, process like normal { var lowPrice = numKids + numSpecNeeds + numCarers + numSeniors; var freeAdults = Math.floor(numKids/10); numAdults -= freeAdults; if(numAdults < 0) { numAdults = 0; } var total = (lowPrice * 5.25) + (numAdults * ; myFormInputs["TOTAL-COST"].value = total.toFixed(2); return true; //ensure the submission happens } } </script> A few things to note: 1. The biggest thing is that this code may not work as-is. I haven't tested it or anything, it was merely written off the top of my head. That said, I think something along these lines should work for you. The best way to test it is to run the page through Firefox and report back any errors the error console shows you. Bonus points if you have Firebug installed. 2. Do you ever use the validKids and validAdults variables anywhere? I left them in the function, but they don't appear to do anything. 3. Along those same lines, I tried shortening the amount of code where I could. There were several places where you created a new variable for no real reason. Use only what you need. I also took the liberty of reducing the number of document.blah.blah calls. This, too, saves on typing and, more importantly, processing. Instead of forcing the browser to calculate where form2 is, then all its inputs, then the correct input, then that input's value, I stored some of that info in a variable (myFormInputs). No repeat calculations needed. 4. Similarly, using parseInt for data validation isn't the most elegant solution. You can simplify things if you use regular expressions. I left them out because I didn't want to change your code too much, but it's a simple change. In this case, the brute-force method works because you're expecting a base-10 number in each field, so you'd really only be gaining shorter code by using regex, but with more complex values (text), regex is great. I hope this helps a bit. Let me know of any errors.
-
You should probably post your entire script, as some of what I wrote may change depending on what else is going on inside of it. That way, I can just post a complete modified version that you can use with minimal fuss.
-
The easiest thing to do would be to assign a variable to each population, so: var myForm = document.forms["form2"]; //we use this later var myFormInputs = document.forms["form2"].elements; //better to put all inputs into a variable that we can access...saves on typing and processing var numKids = parseInt(myFormInputs["NUMBER-OF-KIDS"].value, 10); var numSpecNeeds = parseInt(myFormInputs["NUMBER-OF-SPECIAL-NEEDS"].value, 10); . . . Then add them together and see if they exceed 15. Probably best to do this when the form is submitted: myForm.onsubmit = function() { if((numKids + numSpecNeeds + /* all of the other populations */) < 15) { alert("Must be a minimum of 15 people!"); return false; } else { //submit the form normally } }
-
If they're part of the class/object itself, yes. The 'this' keyword refers to the current instantiated object. So: <?php class Example { private $myGoodies; public function __construct($stringVal = null) //object constructor. $stringVal has a default value of null. { $this->myGoodies = $stringVal; } public function setMyGoodies($stringVal) //function to explicitly set $myGoodies to $stringVal if not done so with the constructor { $this->myGoodies = $stringVal; } public function getMyGoodies() { return $this->myGoodies; } } $example1 = new Example(); $example1->setMyGoodies("This is example1"); $example2 = newExample("This is example2"); $example1_output = $example1->getMyGoodies(); $example2_output = $example2->getMyGoodies(); echo "Example 1: $example1_output -- Example 2: $example2_output"; /* Should print: Example 1: This is example1 -- Example 2: This is example2 */ ?>
-
You can preinitialize private variables, so, yes, the following will work: <?php private $foo = "Hi, I'm a private variable!"; ?> You can access/assign to private variables from within the class by using the 'this' keyword, like normal. So: <?php private $foo; public function setFoo($string) { $this->foo = $string; } public function printFoo() { if($this->foo) { echo $this->foo; } else { echo "Foo not set"; } } ?>
-
Page reloading instead of element being displayed...
KevinM1 replied to Perad's topic in Javascript Help
Oh..well...uh.... :blush: Sorry about that. -
Page reloading instead of element being displayed...
KevinM1 replied to Perad's topic in Javascript Help
It's not that document.write() is outdated, it's that it overwrites the document at the beginning rather than append to the document's end. The DOM methods are superior because they allow you to place elements exactly where you want them within the document. -
Try: <script type="text/javascript"> window.onload = function() { var links = document.getElementsByTagName("a"); for(var i = 0; i < links.length; i++) { links[i].onmouseover = function() { window.status = ""; } } } </script>
-
Yeah, scope is a bit weird in JavaScript. I believe it has function-level scope. So, with some block statements: var example = 5; if(myElem.value == "add") { alert("Adding"); example += 2; } document.write(example); It will write 5 instead of 7. It makes sense to leave 'var' out if it was used in a higher level of scope. So: var global = "Hi, I'm a global variable!"; function example() { global += " And this is me in a function!"; } example(); document.write(global); Will output: Hi, I'm a global variable! And this is me in a function! But, if you do this: var global = "Hi, I'm a global variable!"; function example() { var global = ""; global += " And this is me in a function!"; } example(); document.write(global); It will output: Hi, I'm a global variable!
-
I believe it's a reference. It shouldn't really matter, though, as the temporary mSO object will be a unique object each time the function is called. Not only that, but mSO lives only for the lifespan of the function anyway. The 'var' keyword used before it forces scope. The only collision that I think may occur is if you try creating two objects with the same exact options. That's because their IDs would be the same, so the second object would most likely overwrite the first. Actually, now that I think about it, the following should happen. Say you do something like: var myOptions = { id: "Song1", url: "music/rock_on.mp3" }; var musicObj = createSoundObject(myOptions); var musicObj2 = createSoundObject(myOptions); I believe that musicObj and musicObj2 should point to the same object. So, changing something with one variable may change it for both. Of course, this depends on how soundManager behaves under the hood. It may check to see if any duplicate sounds are active. But, generally, they should point to the same object. There's really only one way to know for sure -- create a test page that attempts to create two different objects using the same options for both.
-
I believe it's a reference. It shouldn't really matter, though, as the temporary mSO object will be a unique object each time the function is called. Not only that, but mSO lives only for the lifespan of the function anyway. The 'var' keyword used before it forces scope. The only collision that I think may occur is if you try creating two objects with the same exact options. That's because their IDs would be the same, so the second object would most likely overwrite the first.
-
You shouldn't be passing MSO into the function, as that's what you're trying to create. So, it makes more sense to do something like: function createSoundObject(myId, myUrl) { var mSO = soundManager.createSound( { id: myId, url: myUrl }); return mSO; //gotta remember to return it so it can be assigned to a variable outside of this function } A better way to do it, though, would be to pass it an object filled with options: function createSoundObject(options) { var mSO = soundManager.createSound(options); return mSO; } var myOptions = { id: "some id", url: "some url", onfinish: function() { alert("Hi, I'm the alert telling you that the onfinish event fired!"); } }; var testSoundObj = createSoundObject(myOptions); You keep the flexiblity of the default soundManager.createSound() function, since you can set what options/parameters you like, but save on some typing. Unfortunately, it's difficult creating a function to generate the options object as the soundManager has a ton of properties that can be assigned to. I don't think there's a very clean way to get around some of the grunt work.
-
Using databases as an example, imagine you build a site and need to move it to another host with mssql instead of mysql, or maybe you build a cms that you want to use on different sites. You'll have to go through all of the php and change all the code that deals with mysql databases to mssql. A well written set of database abstraction objects will allow you to run database queries, without worrying about connecting to the database or what kind of database it is. But still can't you do this with functions? Yeah, the DB example isn't the best. Here's one: you have a large site. On each page, you allow the user several different ways to interact with it. They can login, post comments, access database records, etc. It makes the most sense to invoke this functionality dynamically when the user makes a particular request. How can we do that? Well, one method is to have a controller that's nothing more than a switch statement that includes the right script based on the request passed in: <?php switch ($_REQUEST['action']){ case "index": include("index.php"); break; case "login": include("login.php"); break; . . . } ?> This is okay for a small site, but not for one that expects a lot of different possible requests, or for a site that needs to grow or change. It's just too awkward to maintain. Enter OOP. I can do the same thing as above with this: <?php require_once("data/config.php5"); MP_controller_Controller::run(); ?> Obviously, the code that actually does things is hidden within the run() method, and subsequent methods. But, my code is short and sweet. Here's MP_controller_Controller: <?php class MP_controller_Controller{ private function __construct(){} static function run(){ $instance = new MP_controller_Controller(); $instance->init(); $instance->handleRequest(); $instance->display(); } private function init(){} private function handleRequest(){ $request = new MP_controller_Request(); $commandFactory = new MP_command_CommandFactory(); $command = $commandFactory->getCommand($request); $command->execute($request); } private function display(){ $sessReg = MP_base_SessionRegistry::getInstance(); if(!$sessReg->isEmpty()){ $user = $sessReg->getUser(); if($user){ echo "Welcome back, {$user->getName()}<br /><br />\n\n"; } } } } ?> Again, not much to it. The run() method calls four methods of its own: 1. It ensures we have a controller object that we can use in order to execute the proper command. 2. It runs an initialization method (init()). In this case, that method is empty. 3. It runs handleRequest(), which is the heart of the entire operation. 4. It runs display(), which isn't necessary, and added for my own testing. Like I mentioned above, handleRequest() is the interesting part. It creates a new MP_controller_Request object, which is basically a wrapper around $_REQUEST with some helper functions thrown in. I then create a new CommandFactory, which is an object that creates 'commands' based on request data, and retrieve the proper command from it based on a particular user request. Finally, the command executes, doing what it's supposed to do (logging a user into the system, or posting a comment to the site, etc.). Admittedly, this is a lot of up-front work for something small, and there are other objects being used in this operation as well. So, this isn't recommended for small sites. But it's flexible. Need to add more functionality to the site? Add a new command object. Need to modify the way something is done? Modify the command object that represents that process. Need to remove a portion of the site? Remove that/those command object(s). It's as simple as that. No need for dozens of if/else clauses or switch cases. Everything is handled dynamically. Even better, everything is modular. I can use the Front Controller on any site I want. Similarly, I can use the same command on multiple sites without thinking about it. Once you have a foundation of basic objects, you can swap components in and out with very little trouble. Dependencies are minimized as objects, by their very nature, tend to be self-contained. I hope this made some sense. It took me a while to get the point, too, so keep at it. It'll sink in eventually.
-
search string not working with variable reg express
KevinM1 replied to tkm's topic in Javascript Help
You should probably show some more code. Where does 'el' come from? What does the getValue() function do? Do you declare 'i' anywhere? What do you mean by it 'not working'? Is it returning the wrong string? No string? Is it iterating through all 100 elements without exiting when it should find the right one? -
Phew! I'm happy it's finally working. It looks like there was a conflict between the window.onload event and the soundManager.onload event. When you get more comfortable with JavaScript, I recommend getting the book Pro JavaScript Techniques by John Resig. It's a fast-paced book, but it really helped clarify JS for me. Good luck with the PHP backend. Let me know if you need any assistance.
-
I just tried this test. It seems to work okay, but it can't connect to your .swf file, so I can't see if the onclick event handler is working (apparently, sound manage disables everything if something can't load correctly). Let me know if the following works: <script type="text/javascript"> soundManager.onload = function() { soundManager.url = "http://www.birminghammusiclive.com/soundmanager2.swf"; // override default SWF url soundManager.debugMode = false; soundManager.consoleOnly = false; var playerButton = document.getElementById("player"); //need it before the onfinish event var mySoundObj = soundManager.createSound( { id: "mySound", url: "http://www.birminghammusiclive.com/Rick.mp3", onfinish: function() { playerButton.src = "http://www.birminghammusiclive.com/images/bigplay.png"; } }); //uses object literal notation just to be safe playerButton.onclick = function() { if(this.src == "http://www.birminghammusiclive.com/images/bigplay.png") { this.src = "http://www.birminghammusiclive.com/images/bigpause.png"; mySoundObj.play(); } else { this.src = "http://www.birminghammusiclive.com/images/bigplay.png"; mySoundObj.pause(); } //end else } //end onclick } //end onload </script>
-
Unfortunately, from a logical standpoint, you can't use the playState property by itself. It makes no sense to check for it just once, and trying to create a custom loop to keep testing it is a major pain. So, using onfinish is the way to go. Unfortunately, it looks like the soundmanager is having some issues loading. I'm not sure what's causing it, though, because according to the script's documentation, a soundManager object should be globally available from the get-go. So, here's one last attempt at getting it to work. If it doesn't, I suggest contacting the people who made the soundManager library itself. It shouldn't be this difficult to combine it with normal, simple JavaScript. Anyway, here is another attempt: <script type="text/javascript"> window.onload = function() { soundmanager.onload = function() { soundManager.url = 'soundmanager2.swf'; // override default SWF url soundManager.debugMode = false; soundManager.consoleOnly = false; var playerButton = document.getElementById("player"); //need it before the onfinish event var mySoundObj = soundmanager.createSound( { id: "mySound", url: "Rick.mp3", onfinish: function() { playerButton.src = "http://www.birminghammusiclive.com/images/bigplay.png"; } }); //uses object literal notation just to be safe playerButton.onclick = function() { if(this.src == "http://www.birminghammusiclive.com/images/bigplay.png") { this.src = "http://www.birminghammusiclive.com/images/bigpause.png"; mySoundObj.play(); } else { this.src = "http://www.birminghammusiclive.com/images/bigplay.png"; mySoundObj.pause(); } //end else } //end onclick } //end soundmanager.onload } //end window.onload </script>
-
I think you can still use the onfinish event to swap images. Try the following: <script type="text/javascript"> window.onload = function() { soundManager.url = 'soundmanager2.swf'; // override default SWF url soundManager.debugMode = false; soundManager.consoleOnly = false; soundmanager.onload = function() { var playerButton = document.getElementById("player"); //need it before the onfinish event var mySoundObj = soundmanager.createSound( { id: "mySound", url: "Rick.mp3", onfinish: function() { playerButton.src = "http://www.birminghammusiclive.com/images/bigplay.png"; } }); //uses object literal notation just to be safe playerButton.onclick = function() { if(this.src == "http://www.birminghammusiclive.com/images/bigplay.png") { this.src = "http://www.birminghammusiclive.com/images/bigpause.png"; mySoundObj.play(); } else { this.src = "http://www.birminghammusiclive.com/images/bigplay.png"; mySoundObj.pause(); } //end else } //end onclick } //end soundmanager.onload } //end window.onload </script> The biggest difference here is that instead of using the quick version of createSound, I decided to switch it to the object version instead. It allows us to use the playState property in case the above code doesn't work. We can just swap out a few lines of code if need be. Also, onfinish is now part of createSound as well. Since we're now creating a new sound object, it makes sense to add it to the list of object properties. The function is the same, just in a different spot. Let me know if this works.
-
Looking at your code...yeah, it's still a mess. Quick question: is this the code you're actually trying to use, or are you in the middle of rewriting it? Because, right now, things look to be thrown together rather randomly (such as adding the onfinish part to the onclick handler, etc, which is definitely not what I had written before). Onfinish fails, most likely, because the code used to create a sound (createSound("mySound", "Rick.mp3")) is commented out. The '//' in front of it tells the browser to ignore it and treat it like code documentation rather than an actual instruction. Chances are, since there's no sound, as the code that creates it is virtually non-existant, the onfinish event fires automatically. Here's another attempt at getting it to work. Once again, replace ALL of your script code with the following: <script type="text/javascript" src="soundmanager2.js"></script> <script type="text/javascript"> window.onload = function() { soundManager.url = 'soundmanager2.swf'; // override default SWF url soundManager.debugMode = false; soundManager.consoleOnly = false; soundManager.onload = function() { soundManager.createSound('mySound','Rick.mp3'); } var playerButton = document.getElementById("player"); playerButton.onclick = function() { if(this.src == "http://www.birminghammusiclive.com/images/bigplay.png") { this.src = "http://www.birminghammusiclive.com/images/bigpause.png"; soundManager.play("mySound"); } else { this.src = "http://www.birminghammusiclive.com/images/bigplay.png"; soundManager.pause("mySound"); } } //END OF ONCLICK FUNCTION -- DO NOT ADD ANYTHING ELSE TO THIS!!!!!!!!!!!!!!!! soundManager.onfinish = function() { playerButton.src = "http://www.birminghammusiclive.com/images/bigplay.png"; } //END OF ONFINISH FUNCTION -- DO NOT TOUCH!!!!!!!!!!!!!!!! } </script> Here's a verbal description of the code: We wait until the entire page is loaded (window.onload) before we attach our JavaScript to the page. Once it is loaded, we initialize some values, and create functions that are invoked when certain events fire. Event 1: When the sound manager script is loaded (soundManager.onload), we load the correct song (createSound("mySound", "Rick.mp3")). Event 2: When the play button is clicked (playerButton.onclick), we do two simultaneous toggles -- one for the button's image (changing it from pause to play, and back again), and one for the song itself (actually playing and pausing the audio file). Event 3: When the song is finished (soundManager.onfinish), we make sure that the play button has the correct image, telling the user that it can be played again. If soundManager.onload still fails, let me know, but DO NOT attempt to fix it by randomly mashing functions together. They are separate for a reason. Regarding soundManager.onload failing, chances are, you simply need to do a simple assignment to initialize that variable, something like: var soundManager = new SoundManager(); Hold off on doing that, however, until you test the code I wrote above. If it doesn't fix the issue, let me know, so I can find some sound manager documentation and initialize the variable correctly.
-
Does the image toggle work with the full path, though?
-
Nope, because you only have two choices - play or pause. So, to clarify, here's a verbal run through the code: When the image is clicked, we check the current value assigned to its source attribute. If it is the play button, we change it to be the pause button and play the song. Else we know it's currently the pause button (because there are only two possible choices), so we change it to be the play button, and we pause the song. Since there are only two possible choices, we only have to check for one of them. If the check fails (i.e., this.src != "images/bigplay.png"), then you can be sure the other option is the one currently in play. You'll find that most code that toggles element properties is written in a similar fashion.
-
I see what the problem is. You're mixing/matching code without really understanding how to implement the changes that Aaron and I suggested. Okay, here's what to do: 1. Remove the anchor tag. You don't need a hyperlink in order to do onclick things, and since you don't want the user to go to another page, it's ultimately useless to have an anchor there anyway. So, in its stead, simply have: <img id="player" src="images/bigplay.png" alt="audio player control" /> 2. Use unobtrusive JavaScript. What does that mean? It means the elimination of JavaScript function calls from your HTML markup. See how my modified img tag has no JavaScript in it? That's a good thing. It keeps your script code centralized, and makes it easier to implement and debug. Not only that, but there's no need for your markup to have any knowledge of your script. So, replace ALL script code with the following: <script type="text/javascript" src="soundmanager2.js"></script> <script type="text/javascript"> window.onload = function() //this ensures the DOM exists before we start trying to play with it { soundManager.url = 'soundmanager2.swf'; // override default SWF url soundManager.debugMode = false; soundManager.consoleOnly = false; soundManager.onload = function() { soundManager.createSound({id:'mySound',url:'Rick.mp3'}); //NOTE: if this doesn't work, replace it with: soundManager.createSound("mySound", "Rick.mp3"); } var playerButton = document.getElementById("player"); playerButton.onclick = function() { if(this.src == "images/bigplay.png") { this.src = "images/bigpause.png"; soundManager.play("mySound"); } else { this.src="images/bigplay.png"; soundManager.pause("mySound"); } } soundManager.onfinish = function() { playerButton.src = "images/bigstop.png"; //if you have a big stop image...if not, use bigpause.png } } </script> With this, your code will (hopefully) work correctly, and be easier to maintain. Keep in mind, however, that some of this code is making assumptions on how the soundmanager package works. The best thing you can do to test it is to try it in Firefox, and report back any errors the error console finds. Let me know if you need any help doing that.
-
Without looking at the soundmanager code, your custom code looks a bit odd. Basically, you want a toggle, so you'd have to attach an onclick function to your button that does two things: toggles between playing and pausing music, and toggles between showing the play button image and the pause button image. So, pseudo-code, it would be something like: <script type="text/javascript"> //this assumes window.onload = blah blah blah var playerButton = document.getElementById("playerButton"); //whatever element you're using to control the play. playerButton.onclick = function() { if(this.src == "/images/bigplay.png") { this.src = "/images/bigpause.png"; soundManager.play(soundID); } else { this.src="/images/bigplay.png"; soundManager.pause(soundID); } } </script> Again, this is all without looking at the actual sound manager code. Does the sound manager script have an onfinish event you can attach a function to? Because I don't believe something like that exists natively in JavaScript (although I could be wrong).
-
Mwahaha...my plan of foisting my hangups onto others one post at a time is coming to fruition!