~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Post a code which can be run / tested by us. Posting incomplete snippets from here and there won't help. Anyways, what is the problem you are facing right now? Does it work, if not, have you taken a look at the Error Console of Firefox (Tools -> Error Console)? Does it show any errors? If it works but not the way you wanted, what is the expected behavior?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

setTimeout executes a given piece of code / a function after a given amount of time, though not repeatedly. For that, there is always setInterval.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> I've come up with a solution and now I'm addressing the issue of mozilla and ie rendering
> different results on getYear.

Linky

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Another attempt at writing the entire logic in JSP? Anyways the message is pretty self explanatory; the JSP engine was unable to compile the JSP to a Servlet due to compile time errors. J2EE tutorial 1.5 / 1.4 along with a good book might do a lot more good than following some old/outdated online tutorials.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Try using UrlRewriteFilter for serious uses or using a servlet for controller and making appropriate entry in the web.xml file.
With URLRewrite it would be something along the lines of:

<rule>
    <from>^/products/([0-9]+)$</from>
    <to>/products/index.jsp?product_id=$1</to>
    </rule>

For e.g. suppose you have a controller which handles the application flow, the web.xml would look like something:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">
   
  <description>Testy-web-app</description>
  <display-name>Servlet and JSP Examples</display-name>

  <servlet>
    <servlet-name>Controller</servlet-name>
    <servlet-class>home.projects.testy.servlet.ControllerServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Controller</servlet-name>
    <url-pattern>/products/*</url-pattern>
  </servlet-mapping>
  
</web-app>

You home page would look something like:

<html>
  <head>
    <title>Product database</title>
  </head>
  <body>
    <div>
      Please choose a product:
      <ul>
        <li><a href="./products/product1">Product 1</a></li>
        <li><a href="./products/product2">Product 2</a></li>
      </ul>
    </div>
  </body>
</html>
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Math.random() along with the article on generating random numbers should get you going. Even though the article uses C/C++, adapting the algorithm to Javascript shouldn't be a big problem.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> But, more often than not, I'd have a good idea what x is going to be, and would normally
> only ever use null as placeholder for things that I'm sure are only going to otherwise be
> objects

Again fails if you end up explicitly constructing Boolean, String and Number objects since they suffer with the same drawbacks as their primitive counterparts.

> But yeh, that only works if you keep the collection homogenous..

...which almost never is the case with real world Javascript object literals. :-)

Anyways, the intent of my posts was not to nitpick at the code snippets which almost always work in normal cases, but to make it clear to the OP that dark corners do exist in the happy go lucky world of Javascript.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> Can, of course use if ( ( x !== undefined ) & ( x !== null ) ) , but it doesn't really gain
> very much over if( x ) .

Err..no, it very much does since blank strings, the boolean value false and the integer 0 all evaluate to false. Consider:

var person = {name: "sos", hostile: false, description: ''};

if(person["hostile"]) {
  // Even though a mapping exists for they key 'hostile', 
  // the program flow doesn't enter this block.
}

if(person["description"]) {
  // ditto here.
}

Also it is much better to base your test of undefined on typeof rather than comparison operator since comparison fails for non-existent variables. Consider the following two almost similar snippets. The first one doesn't work, the second one does:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test</title>
</head>
<body>
  <script type="text/javascript">
  alert(a === undefined);  
  </script>  
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test</title>
</head>
<body>
  <script type="text/javascript">
  alert(typeof a === "undefined");
  </script>  
</body>
</html>
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> But only because I'd rarely make a meaningful working distinction between ( or differently
> handle ) an object variable being null or being undefined. null is a valid value, undefined is *nothing*. Undefined has a special significance in the sense that attempting to retrieve value for a non-existent key from a Javascript object returns undefined . Simply put, the distinction is important when:

if(x) {
  // do something
}

isn't acceptable. :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> Note that setSize() is not a member of ConfirmExitDialog() but inherited from a super
> class... now "this" is used to access it??? this simply stands for the reference to current instance in consideration. The execution of setSize() is no different than this.setSize() for the very same reason. They both end up calling the Parent class's method setSize() or throwing a compile time error in case no such method exists. This look up is not restricted to the parent class but continues down the inheritance hierarchy. To sum it up, this , when used in instance method and constructor refers to the current instance executing that very method / constructor.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

If you are using Ajax, you can use the responseXML property which contains the document as an XmlDocument object that you can manipulate using DOM methods.

// Error handling omitted for brevity.
var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.com/', true);
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200) {
       // make sure the XML is well formed otherwise 'xml' will be null
       var xml = req.responseXML;
       // grab hold of the first DIV reference
       var divObj = xml.getElementsByTagName("div")[0];
     }      
     else {
      dump("Error loading page\n");
     }
  }
};
req.send(null);
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> Null also compares to undefined: ( undefined == null ) is always true.

...which is often misleading as they stand for two different things and have different types. A better way in almost all cases would be to use the strict comparison operator to get an accurate, type safe result.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

When she told him he was average, was she just being mean?

Mean, no. Ironic, yes. :-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Using normal HTML with embedded JSP tags. Take a look at the generated HTML markup by JSF and you will get a fair idea of how things are rendered under the hood.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> even null is not equal to null

window.alert(null === null);

There ya go!

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Then it won't work since insertBefore expects both arguments to be DOM element references. It works in IE since in IE the name of the element also contains the element reference. IMO, something like this should work:

var myDiv = document.getElementById("ContactFormDiv");
var myFrm = document.forms["ContactForm"];
myDiv.insertBefore(loadingImg, myFrm);

If it still doesn't work, look at the Error Console of Firefox which serves as a poor man's debugging utility. (Tools -> Error Console)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
> document.getElementById("ContactFormDiv").insertBefore(loadingImg, ContactForm);

Where have you defined ContactForm?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Google for Ajax date picker.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> So much nicer if data would be retrieved from DB in servlet,

Not to mention that actually *nothing* should go in servlet except the processing of request parameters / attributes and invocation of the actual business logic components. This helps in ensuring that you don't repeat yourself when the view changes. E.g. from a web based application to a swing based application.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> String ip = "10.23.14.5"; //the ip of the database, in your case it would be localhost

Prefer configuration over code; the URL for the database along with the database name almost always comes from a configuration file. Also for database intensive applications/operations, consider using a Connection Pool instead of grabbing raw connections. Connection object creation is an expensive activity giving the fact that your application will perform a lot many short lived Database activities. Connection pools give your the power of configuring a variety of parameters like the pool size, the connection purge policy etc.

> String query="select username, password from users where username='"+user+"' and 
> password='"+pass+"'";

Vulnerable to SQL Injection. Using Prepared Statements prevents this as well as the Statement pooling offered by a lot many Type 4 drivers reduces the execution time.

>

u.equals(user))&&(p.equals(pass))

Though not applicable to this discussion maybe, password are almost always never stored in plain text format. Consider encrypting your passwords and salting them. Industry strength J2EE applications also make use of a LDAP for authentication instead of storing passwords in plain old database tables. They provide you the flexibility of organizing the users of your application in groups and hierarchies and their easy management.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Your best bet would be to intercept the point in the data flow which is causing this behavior. Before sending the Ajax request, do an alert and see whether is it an issue with the data being passed to the server. Try logging the data received at the server to see if it is an issue when transmitting data over the wire and / or incorrect encoding used. And lastly, log the data before being inserted into the database, which might bring out issues with data processing.

Without looking at the code, it would be difficult to come to a conclusion. After all, it might be a problem with the server side processing code which might require you to post the same question along with the ASP code in the ASP forum.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> If not, why haven't developers pushed to have such an object created

Pop-ups are a usability concern and are almost always handed by different browsers and specialized pop-up blockers in different ways. What would you gain from detecting whether pop-ups are blocked or not? If navigate the user to a separate page, then why not use the same technique instead of different flows for users. IMO, if a user don't want to see anything that involves pop-ups, any content which those pop-ups contain mean nothing.

> Specific objects that would help me refine detection of IE based browsers and Opera.

Your best bet would be to look at any of the existing popular Javascript frameworks since they make sure object detection to the highest degree is made possible so that the API calls can be as transparent as possible.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I can understand that kids at your age are rebellious. Come back after a few years and you might just be mature enough to enjoy/understand this one. Till then, happy cribbing/trolling.

iamthwee commented: Nice comeback? +15
TheNNS commented: wtf? you think i'm 10? -1
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

No, both your usages of isNaN won't work since they would also work for input such as "3E3". A better way would be to make sure that your form field only contains dots and digits. Also in both the cases, there is an implicit conversion from Javscript String object to Number object. A better way would be create a Number object out of the form field input and then pass it to isNaN function since it can then be reused.

The way a isNaN function works is that it tests whether the input passed to it is Not A Number. If the input is a string, it is then converted to a Number object using the normal parsing rules. If the input is invalid, the Number construction results in a NaN which when passed to isNaN returns true.

Concerning your validations, they can become a lot easier if you know how to use Regular Expressions. A simple example would be (untested):

var nameRegex = /^[a-zA-Z]+$/;
var zipRegex = /^\d+$/;
var someName = "sos";
var someZip = "3434";
if(nameRegex.test(someInput)) {
  window.alert(someName + " is a valid name.");
}
if(zipRegex.test(someInput)) {
  window.alert(someZip + " is a valid zip code.");
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The craft of good design comes from knowing what a bad design is. Unless you do something wrong, you won't know what is right. It's about time you started implementing something and stopped achieving maximum perfection. Re factoring is a part and parcel of software development and IMO is the thing which makes you learn. This thread has many good contributions so the only thing which remains to be done is; Just do it!

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> I know it's kinda against the rules

And the reason it is against the rules is because instead of the thousands of beginners / needy out there, only a single person gets the solution. Reading individualistic emails / PM's would be kind of difficult given the little time I get for helping people out, not to mention the moderation duties which need to be performed. I hope you understand.

You have been supplied with a lot of good ideas and I am pretty sure you will be able to come with a relatively better implementation than your peers. And hey, getting things right in the first go is kind of a sin. :-)

Alex Edwards commented: Lol, I suppose so. Thanks for all of your help! +1
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> It's always the little things that trip one up. Thanks a bunch! :D

You are welcome. Also please make sure you mark the thread as solved if your query is answered by clicking the 'Mark as solved' link.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Javascript has variables, no? You can use them to maintain the state of your calculator app.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> For example, in the Piece constructor, I simply give an array of Positions the piece will be
> governed by, and code around the possible positions the piece can move from/to ?

Huh? I thought it was pretty clear that Piece should *not* have inking as to what it has to do. It goes something along these lines. A 'Player' makes a 'Move'. The 'CheckerEngine', validates the move, does the necessary operations and updates the 'Board'.

> This can easily be changed by adding a 3rd dimension to the points and simply coding
> around it.

It's just a thought, I am not asking you to add a third dimension but abstract away the dimensional aspect of your game by encapsulating it in a class so that the contract of the methods which use them doesn't change, only the implementation does. Something roughly along the lines of:

public class Position {
  private int x;
  private int y;
  // and many other things
}

// With the position abstraction for 2D
public void renderPiece(Position pos) {
  // Draw something at (x, y)   
}

// With position abstraction for 3D
public void renderPiece(Position pos) {
  // Draw something at (x, y, z)   
}

// Without position abstraction for 2D
public void renderPiece(int x, int y) {
  // Draw something at (x, y)   
}

// Without position abstraction for 3D
public void renderPiece(int x, int y, int z) {
  // Draw something at (x, y, z) …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> I've been banging my head against the wall all week on this, and I don't think I have much
> skull left!

Here, I will put you out of your misery. :-)

Anyways, the bug in the program is pretty apparent here given that you make use of global variables in a recursive call. The variable 't' declared in the function AlertArray has global scope given that it is not prefixed with var.Hence, instead of each invocation of the function having its own copy of the counter 't', each function invocation uses the same variable 't' and hence it ends up never being incremented.

TestObj.prototype.AlertArray = function() {
  document.write("<br>TestObj " + this.ID);
  for (var t = 0; t < this.TestArray.length; ++t) {
    this.TestArray[t].AlertArray();
  }
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Design choices you make have to direct impact on your thought process. Had not the pieces implemented the Moveable interface, would the flow have remained the same? Does the ' Moveable ' interface logically make sense? And now do you really think that 'GameBoard' sounds like an Interface name or more so like a name of a Class? Would it make any difference if it were not an interface? Does making it an Interface solve any immediate problem you face?

I still see that you aren't using the abstraction called ' Position ' to hide the gory 2D details of your game. Instead of implementing the additional 'user friendly' features, concentrate on such finer points and you might end up getting more grades than those you focus on the immediate solution at hand. Also does displayBoard() really do all the rendering activity? If yes, then you need to rethink the design since it's really not the responsibility of the Engine to render the board. An alternate design here might be to have a RenderAble interface which is implemented by all the rendering classes like PieceRenderer , BoardRenderer and have methods like draw() , refresh() etc. The way you use these classes would be to have a constructor which takes a reference to Piece and Board respectively which would be with the Game. There are almost infinite possibilities out there when coming up with the design though the best would be the one which doesn't need any explaining to even …

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Are all the people who have contributed to this thread sane enough for another one? ;-)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Hope you have gone through enough S.H.I.T. in humor to understand this one. :-)

Ancient Dragon commented: LOL :) +34
itdupuis commented: good stuff, keep it up! +1
Scuppery commented: dude that was so good I had to put it on myspace...keep it up +1
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes, the concept seems to be useful, at least for those who are new to forum based systems though the downside here is that regular posters will have to go through an extra click to post their replies.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

AFAIK, there is no reliable way of capturing the page unload event hence not possible. The maximum you can do is come up with some browser specific mumbo jumbo which would surely fail in other browsers. The only reliable way is to keep sending postbacks to the server using Ajax i.e. making an Ajax call every ten seconds / one minute with the updated values.

Since it seems that you are trying to set non-dynamic values (username), a even better way would be to set the Cookies on page load.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> Add a counter pause/unpause button.

Set a Javascript variable which would be checked before invoking your countdown function. As soon as the 'Pause' button is clicked, set the flag variable, store the state of your counter variables and clear the timeout. As soon as the 'UnPause' button is clicked, just unset the flag, start the timeout again with the previous saved counter state.

> Need this timer to survive postbacks (I have another button on the form and on press it
> fire postback and reset a counter)

Save the value of the updated counter in your session variable and read it again when the page loads. As far as reading the updated counter values at the server is concerned, save the state of the counter variable in a hidden field and at the server do something along the lines of Request("updatedState").

> When counter reaches zero I have to do any server side command (for example,
> Label2.Text="Time is up" , where label2 is a server control)

This might be a better answered in the VB.NET forums since Javascript as such doesn't understand any 'server controls'.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

A solution has already been suggested to you. Move the dynamically generated Javascript out of the looping construct. To understand more, take a look at the generated source code by navigating to 'View' -> 'View Source' in Firefox.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> I really like the idea of pieces not being capable of moving but knowing their legal moves.

I am yet to see a game where the pieces don't move. Each and every piece is capable of moving though the set of legal moves differ from game to game. IMO, the pieces should be capable of moving be always passed a valid position so that they can dumbly and safely move to the position mentioned. Maybe a common interface like Moveable should do the trick here. Also consider abstracting the 'position' concept in your game inside a class which will provide you the flexibility of switching between 1D, 2D and 3D.

Since you are into a client server architecture, you might as well have a Game class whose instance will be a game in progress having attributes like total game time, the game name, the reference to the board in use and the players involved in the game.

There are many other finer points which come to mind but I think the above mentioned ones should get you going.

Alex Edwards commented: Totally approved =) +1
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

My suggested solution was to use the Number constructor so as to perform addition as well as validation in a single go. But some additional validation will always be required to prevent inputs like 1E2 creeping through and giving unexpected results.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Glassfish is a full fledged application server while Tomcat is just a servlet container. The choice of which to use depends on your purpose of using the same.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> concentrate on eval() function in javascript by googling

As in concentrate on swatting a fly with a hammer? eval sort of fires off a mini-compiler which dynamically evaluates the string passed to it. Look for better ways of doing things and use eval only when required. E.g. when evaluating a random expression entered by the user when creating a calculator application in Javascript.

> You should use parseInt .

Surprise surprise!

parseInt("09") + parseInt("09")

Moral: Always specify the base when using parseInt .

> This additionally ensures that values like: 1.356 + 6.32 don't get rounded into a sum of
> say 7, so you get the correct value of 7.676

I would still stay away from all those parseXXX variations since they give results which you least expect.

alert(parseFloat("1asldfjas"));
alert(Number("1asdfsdf"));
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

This bug has already been brought up in the Mod section with still no reply. Maybe solving that thread will solve this one too.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

...or just look at the Error Console in Firefox to get the most out of the goodies provided out-of-the-box with your browser. If you still can't pinpoint the cause, step by step debug using Firebug is the way to go.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> Is further clarification needed or can I assume the moderators are speaking on behalf of
> admin?

Considering that this is a 'Feedback' forum, I just presented my view point as a plain old member of Daniweb.

Though I completely understand the logic behind your concern, by deleting snippets such as these, we might just be labeled as a little too restrictive or uptight forum.

But if what you reported can cause trouble to Daniweb on the legal front, I am unwillingly with you.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Just another code snippet?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

A free book 'Processing XML with Java' contains an in depth explanation about working with Java and XML.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> unable to swap images using arrays in javascript

Not surprising considering that the marquee tag is non-standard, deprecated and has no onclick attribute.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The getElementsByName seems to be flawed when working with dynamically added elements in IE. I guess adding elements by using innerHTML is the only way of making IE aware of the existence of new elements.

Anyways, try something simple like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example</title>
    <script type="text/javascript">
    /**
     *  Dynamically create form elements with incremental names.
     *
     *  @param tableId The ID of the table element.
     *  @param elemName The name of the element to be dynamically created.
     */
    function addRow(tableId, elemName) {
      if(!tableId || !elemName) return;
      
      // Grab hold of a reference to the table element and return from the 
      // function if no table element exists for the given table id.
      var tblElem = document.getElementById(tableId);
      if(!tblElem)  return;
      
      // Insert a new row at the end of the table, a new cell at the start
      // of that row and a new text node to the newly created cell.
      var newRow = tblElem.insertRow(-1);
      var newCell = newRow.insertCell(0);
      var txtElem = document.createElement("INPUT");
      txtElem.name = elemName + "[" + (tblElem.rows.length - 1) + "]";
      newCell.appendChild(txtElem);
    }
    
    function getElementsThatStartWith(frmObj, str) {
      if(!str || !frmObj)  return;
      var elems = frmObj.elements, returnElems = [];
      for(var i = 0, maxI = elems.length; i < maxI; ++i) {
        var elem = elems[i];
        if(elem.name.indexOf(str) == 0) {
          returnElems[returnElems.length] = elem;
        }
      }
      return(returnElems);
    }
    
    function validateHobbies(frmObj) {
      var elems = getElementsThatStartWith(frmObj, "hobby");
      for(var i = 0, maxI = elems.length; i < …
jakesee commented: Very professional programmer +1
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

> var numeric = /^[0-9]*$/ This isn't a valid RegExp since it also validates a blank string. Numeric RegExp validation would go something along the lines of /^[0-9]+$/ or simply /^\d+$/ . [0-9] stands for any numeric character (0-9) where - is the range operator. Regular expressions are different beasts altogether, a single post won't suffice the purpose of explaining it all to you. Read up more on it here.

OmniX commented: Very useful post and link. Thankyou! +1