RSS

Category Archives: Mixed

Restrict text field to accept only numeric number in javascript

First write the following two functions:

function extractNumber(obj, decimalPlaces, allowNegative)
{
 var temp = obj.value;

 // avoid changing things if already formatted correctly
 var reg0Str = '[0-9]*';
 if (decimalPlaces > 0) {
  reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
 } else if (decimalPlaces  0 && temp.charAt(0) == '-';
  var reg2 = /-/g;
  temp = temp.replace(reg2, '');
  if (hasNegative) temp = '-' + temp;
 }

 if (decimalPlaces != 0) {
  var reg3 = /\./g;
  var reg3Array = reg3.exec(temp);
  if (reg3Array != null) {
   // keep only first occurrence of .
   //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces  0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
   temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
  }
 }

 obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
 var key;
 var isCtrl = false;
 var keychar;
 var reg;

 if(window.event) {
  key = e.keyCode;
  isCtrl = window.event.ctrlKey
 }
 else if(e.which) {
  key = e.which;
  isCtrl = e.ctrlKey;
 }

 if (isNaN(key)) return true;

 keychar = String.fromCharCode(key);

 // check for backspace or delete, or if Ctrl was pressed
 if (key == 8 || isCtrl)
 {
  return true;
 }

 reg = /\d/;
 var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
 var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

 return isFirstN || isFirstD || reg.test(keychar);
}

Then use the above functions from your input field as follows:

<input type="text" onblur="extractNumber(this,-1,false);" onkeyup="extractNumber(this,-1,false);" onkeypress="return blockNonNumbers(this, event, true, false);" />
 
Leave a comment

Posted by on June 23, 2011 in JavaScript, Mixed

 

Tags:

Validate numbers in JavaScript

Check your input with the following function:

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

You can use another function:

function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}

The (input – 0) expression forces JavaScript to do type coercion on your input value; it must first be interpreted as a number for the boolean compare. If that conversion to a number fails, the expression will result in NaN. Then this numeric result is compared to the original value you passed in. Since the left hand side is a number, type coercion is again used. They should always be the same (always true), but there’s a special rule that says NaN is never equal to NaN, and so a value that can’t be converted to a number will always return false. The check on the length is of course for the empty string special case. In summary, if you want to know if a value can be converted to a number, actually try to convert it to a number.

Note that it falls down on your 0x89f test, but that’s because in many environments that’s an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that’s your reason for not using isNaN() then just wrap your own function around isNaN() that can also do the additional check.

Here is another one:

function isNumeric(input) {
var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
var regex = RegExp(number);
return regex.test(input) && input.length>0;
}

Integer value can be verified by:

function isNumeric(value) {
var bool = isNaN(+value));
bool = bool || (value.indexOf('.') != -1);
bool = bool || (value.indexOf(",") != -1);
return !bool;
}
 
Leave a comment

Posted by on June 21, 2011 in JavaScript, Mixed

 

Using Namespaces to Prevent Conflicts

If you’re doing an extensive amount of raw JavaScript coding and suspect that additions could be made to the same pages you’re working on, you can prevent any future conflicts with your code by giving your code its own namespace.

Object-oriented JavaScript implements namespace-like principles due to the fact that properties and methods are declared inside of objects, thus there are less likely to be conflicts. A conflict could arise, however, through object names. And very likely, the conflict will occur “silently”, thus you may not be alerted to the issue immediately.

You can prevent all conflicts by creating a unique namespace. Let’s use the showStatistics function to demonstrate how we can encapsulate code into its own namespace:

if (typeof MY == "undefined") {
  MY = new Object();
  MY.CUSTOM = new Object();
}

MY.CUSTOM.namespace = function() {
  function showStatistics(args) {
    document.write("

Name: " + args.name); document.write("Team: " + args.team); if (typeof args.position === "string") { document.write("Position: " + args.position); } if (typeof args.average === "number") { document.write("Average: " + args.average); } if (typeof args.homeruns === "number") { document.write("Home Runs: " + args.homeruns); } if (typeof args.rbi === "number") { document.write("Runs Batted In: " + args.rbi + "

"); } } showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 }); } MY.CUSTOM.namespace();

The first few lines create the namespace by checking to see if the “MY” object already exists. This object can be whatever you want it to be. Just pick a name that you don’t think will ever be used again. After the MY object is created, we are then able to create the “CUSTOM” object as a property of the MY object. Then our namespace function becomes a method of the MY.CUSTOM object. Keep in mind that “MY”, “CUSTOM” and “namespace” can each be your own custom names. I chose these for demonstration purposes. They could be CHEESEBURGER.ONIONS.pickles if you want!

The showStatistics function is exactly the same as in the example earlier that utilizes an object literal to pass in the values. But in this case, the entire function, including the object literal, is encapsulated inside my.custom.namespace. The last line invokes the entire function using dot notation, and the function runs exactly the same as it normally would, except that it is protected from conflicting with another function called “showStatistics”.

 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Mixed

 

Contextual Targeting of DOM Elements

There are sometimes instances where you need to traverse the DOM and gain access to a specific element, or group of elements, but due to certain restrictions, you may not have direct access to the elements via a CSS class name or ID in the HTML code. This might be because of user-generated content produced through a rich text editor, or dynamic content pulled from a database.

Whatever the case, it’s not impossible to access those unidentified DOM elements via JavaScript. Using what I call “contextual targeting”, you can gain access to, and modify, almost any element in the DOM. As long as you have a map of the general template that contains the element you want to target, you can access that element and manipulate it the same way you would an element that has a class name or ID.

Let’s create some basic HTML code that will serve as our example page:

<div id="header">
  <h1>Site Title</h1>
</div>
<div id="sidebar">
  <ul>
    <li><a href="#">Testing</a></li>

    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>

    <li><a href="#">Testing</a></li>
    <li><a href="#">Testing</a></li>
  </ul>

</div>
<div id="content">
  <h2>Page Title</h2>
  <p><a href="#">Lorum Ipsum link here</a>. Pellentesque habitant morbi
     tristique senectus et netus et malesuada fames ac turpis egestas.
     Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
     ante. Donec eu libero sit amet quam egestas semper.
     Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
     Pellentesque habitant morbi tristique senectus et netus et malesuada
     fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
     ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
     egestas semper. Aenean ultricies mi vitae est. Mauris
     placerat eleifend leo.</p>

  <p><span style="color: red;">Pellentesque habitant morbi</span>
    tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum
    tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec
    eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Pellentesque habitant morbi tristique senectus
    et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
    feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit
    amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat
    eleifend leo.</p>
</div>
<div id="footer">
   <p>Copyright | <a href="#">contact</a> | <a href="#">policy</a> |
      <a href="#">privacy</a></p>

</div>

Using the HTML code above, if we wanted to target all the anchor tags on the page, we could collect them and manipulate them like this:

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  // do something with the anchor tags here
}

If we wanted to target only the anchor tags in the footer, however, we would target them based on their context, or surrounding elements, like this:

var myFooterElement = document.getElementById("footer");
var myLinksInFooter = myFooterElement.getElementsByTagName("a");
for (i=0;i<myLinksInFooter.length;i++) {
  // do something with footer anchor tags here
} 

The first line grabs a reference to the footer element. The second line collects all anchor tags inside the footer. Then we loop through them and do what we want with them. Thus, they are accessible even though they are not grouped via class names.

You can accomplish the same thing by using node properties, as shown below.

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].parentNode.parentNode.id === "footer") {
    // do something with footer anchor tags here
  }
} 

Similar code could be used to target the lone anchor tag inside the “content” section.

We could also limit our anchor tag search to include only tags that have the href attribute set, so as to avoid finding any in-page links. We do this by using the getAttribute method:

var myLinkCollection = document.getElementsByTagName("a");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].getAttribute("href")) {
    // do something with the anchor tags here
  }
}

Finally, you’ll notice that there is a tag with an inline style. The inline style could have been generated through a content management system, so you may not have the ability to edit it directly. You can target all elements with inline styles like this:

var myLinkCollection = document.getElementsByTagName("span");

for (i=0;i<myLinkCollection.length;i++) {
  if (myLinkCollection[i].getAttribute("style")) {
    // do something with all anchors that have inline styles
  }
}  
 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Mixed

 

Object Literals to Pass Optional Arguments

Instead of passing the large number of arguments in the conventional fashion, which could unnecessarily complicate the function, you can pass just one argument which ends up being a collection of arguments declared in an object literal.

Let’s look, first of all, at how we might do this in the typical manner, so we can see the contrast:

function showStatistics(name, team, position, average, homeruns, rbi) {
  document.write("

Name: " + arguments[0]);
  document.write("Team: " + arguments[1]);

  if (typeof arguments[2] === "string") {
    document.write("Position: " + position);
  }
  if (typeof arguments[3] === "number") {
    document.write("Batting Average: " + average);
  }
  if (typeof arguments[4] === "number") {
    document.write("Home Runs: " + homeruns);
  }
  if (typeof arguments[5] === "number") {
    document.write("Runs Batted In: " + rbi + "

");
  }
}
showStatistics("Mark Teixeira");
showStatistics("Mark Teixeira", "New York Yankees");
showStatistics("Mark Teixeira", "New York Yankees", "1st Base", .284, 32, 101);

The function above can take up to 6 arguments. The first two arguments are mandatory, so inside the function, we don’t check for their existence. The last 4 arguments are not mandatory, so we only display their values if they exist.

We call the function 3 different times (last 3 lines), with different numbers of arguments each time. You can see that if the number of passed arguments was in the dozens, or more, the code could look a little messy, and would be harder to maintain, or read.

Now let’s look at the same code using object literals to pass the arguments:

function showStatistics(args) {
  document.write("Name: " + args.name);
  document.write("Team: " + args.team);
  if (typeof args.position === "string") {
    document.write("Position: " + args.position);
  }
  if (typeof args.average === "number") {
    document.write("Average: " + args.average);
  }
  if (typeof args.homeruns === "number") {
    document.write("Home Runs: " + args.homeruns);
  }
  if (typeof args.rbi === "number") {
    document.write("Runs Batted In: " + args.rbi);
  }
}

showStatistics({
  name: "Mark Teixeira"
});

showStatistics({
  name: "Mark Teixeira",
  team: "New York Yankees"
});

showStatistics({
  name: "Mark Teixeira",
  team: "New York Yankees",
  position: "1st Base",
  average: .284,
  homeruns: 32,
  rbi: 101
});

Technically, this second method of passing the arguments might require a little bit more code, but with a large collection of arguments, there are a few advantages.

First, the function itself is simplified because it accepts only one argument (args), which is a collection of all the values passed from the object literal (name, team, position, etc). Plus, the actual argument values are easy to read, and can easily be understood, updated, or modified, since the correlation between the values and the argument references are more direct.

If the function required only a small number of arguments, then this method would not be necessary, and might actually have the opposite effect. So, use this technique sparingly, and only in situations where you foresee the collection of arguments being hard to maintain over time.

 
Leave a comment

Posted by on June 13, 2011 in JavaScript, Mixed

 

JavaScript XMLHttpRequest readyState values

In JavaScript, possible readyState values after sending an XMLHttpRequest are:

0 = open has not yet been called
1 = send has not yet been called but open has been called
2 = send has been called but no response from server
3 = data is in the process of being received from the server
4 = response from server has arrived

 
Leave a comment

Posted by on June 10, 2011 in JavaScript, Mixed

 

JavaScript XMLHttpRequest responseText Property

Once an XMLHttpRequest has been initiated, sent and a response received, the XMLHttpRequest will have a responseText property. This property contains the server response, excluding headers.

Note that responseText is not fully loaded until the XMLHttpRequest readyState is 4. The responseText property can also contain a partial portion of the final result text if readyState is 3, which means that data is in the process of being received from the server.

To access this property: If an XMLHttpRequest call is saved in a variable named objXHR, the responseText can be accessed as objXHR.responseText.

 
Leave a comment

Posted by on June 10, 2011 in JavaScript, Mixed