Flipkart
Thursday, June 3, 2010
Word Jumbling
Here is the little JavaScript ‘program’ to do word jumbling written by James Padolsey.
The first component is a function which jumbles a string’s characters:
function jumble(word) {
// Rand function will return 2-part array
// [0] -> Index of rand, [1] -> random found value (from args)
var rand = function(){
var myRand = Math.floor(Math.random() * arguments.length);
return [myRand, arguments[myRand]];
},
// Split passed word into array
word = word.split(''),
// Cache word length for easy looping
length = word.length,
// Prepate empty string for jumbled word
jumbled = '',
// Get array full of all available indexes:
// (Reverse while loops are quickest: http://reque.st/1382)
arrIndexes = [];
while (length--) {
arrIndexes.push(length);
}
// Cache word length again:
length = word.length;
// Another loop
while (length--) {
// Get a random number, must be one of
// those found in arrIndexes
var rnd = rand.apply(null,arrIndexes);
// Append random character to jumbled
jumbled += word[rnd[1]];
// Remove character from arrIndexes
// so that it is not selected again:
arrIndexes.splice(rnd[0],1);
}
// Return the jumbled word
return jumbled;
}
The second component get’s the value of the textarea on each keyup event and jumbles all characters between the first and last letter of each word: (It also has a primitive way of handling simple punctuation)
$('textarea').keyup(function(){
var text = $(this).val().split(/\s/g),
converted = '';
$.each(text, function(i,word){
if(!word.length) return;
// Extract punctuation:
var puncPattern = /[,\.;:'!\?]+/,
punc = word.match(puncPattern) ? word.match(puncPattern)[0] : '',
puncIndex = word.search(puncPattern),
word = word.replace(punc,'');
// Compile new word, split to array:
var newWord =
(word.length > 2 ?
word.substr(0,1) + jumble(word.substr(1,word.length-2))
+ word.substr(word.length-1)
: word).split('');
// Insert punctuation back in:
newWord.splice(puncIndex,0,punc);
// Add space after word:
converted += newWord.join('') + '\u0020';
});
// Inserted jumbled test into receiver:
$('#receiver').text(converted);
});
You can see a demo of the above script here.
Window Close Event
<head>
<title>Window Close Event</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
</head>
<body>
</div>
</body>
</html>
Tuesday, April 6, 2010
Opening a file download dialog from a JavaScript function
function startDownload()
{
var url='http://server/folder/file.ext';
window.open(url,'Download');
}
< /script >
hide JavaScript errors from the user
return true;
});
Tuesday, March 16, 2010
Jquery: Ajax Function
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
for more detailed Information:
http://api.jquery.com/jQuery.ajax/
Monday, March 15, 2010
JS:Bookmark & Share Widget
For more Information:
http://www.addthis.com/
Tuesday, March 9, 2010
JS:Add/Remove rows from table
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
<input onclick="addRow('dataTable')" type="button" value="Add Row" />
<input onclick="deleteRow('dataTable')" type="button" value="Delete Row" />
<table border="1" id="dataTable">
<tbody>
<tr>
<td><input name="chk" type="checkbox" /></td>
<td><input name="txt" type="text" /></td>
<td><select name="country">
<option value="in">India</option>
<option value="de">Germany</option>
<option value="fr">France</option>
<option value="us">United States</option>
<option value="ch">Switzerland</option>
</select>
</td>
</tr>
</tbody></table>
Monday, March 8, 2010
JS:Get all SelectBox Options for adding hidden field
hiddenfield = document.form.hidden;
if(hiddenfield.value.length > 0) hiddenfield.value="";
for (i=0;i < lb.length;i++) {
if (!isNaN(lb.options[i].value)) {
if(hiddenfield.value.length > 0)
hiddenfield.value = hiddenfield.value + "," + lb.options[i].value;
else
hiddenfield.value = hiddenfield.value + lb.options[i].value;
}
}
Saturday, March 6, 2010
JS: Dynamically add Options in Selectbox
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
try {
combo.add(option, null); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
</script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
<input type="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" id="combo"></select>
</fieldset>
Friday, August 7, 2009
Adding and Removing Options in Selectbox Using JS
function addoption(text,id) {
var feed = document.form.selectboxname;
var flag=true;
for (i=0;i<feed.length;i++) &&="" (!flag)="" (feed.options[i].value="=id)" (feed.selectedindex="" );="" alert(="" already="" feed.options[feed.length]="new" feed="document.form.selectboxname;" flag){="" flag="false;" function="" id);="" id="" if(text="" if="" inserted="" option(text,="" remove_category()="" var="" {="" }="" }else{="">= 0) feed.remove(feed.selectedIndex);
}</feed.length;i++)>
Wednesday, August 5, 2009
Charecter Count
function countLineBreaks(obj){
var iLength = obj.value.length;
var strLineBreaks = obj.value.match(new RegExp("(\\n)", "g"));
var countLineBreaks = strLineBreaks ? strLineBreaks.length : 0;
return countLineBreaks;
}
function textCounter(field, counter_field, maxlimit) {
var lineBreaks = countLineBreaks(field);
var adjust = isInternetExplorer ? 1 : 0;
if (field.value.length - lineBreaks * adjust > maxlimit){
field.value = field.value.substring(0, maxlimit + lineBreaks * adjust);
field.focus();
} else {
counter_field.value = maxlimit - field.value.length + lineBreaks * adjust;
}
}
textarea name="summary_desccription" id="summary_description" rows="5" onKeyDown="textCounter(this.form.summary_desccription,this.form.remLen,10);" onKeyUp="textCounter(this.form.summary_desccription,this.form.remLen,10);"
Wednesday, July 15, 2009
User Name validation
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
//alert(charCode);
if((charCode >= 65 && charCode <= 90) || (charCode >=97 && charCode <= 122) || charCode == 32 || charCode == 8 || charCode == 0 || charCode == 46)
return true;
return false;
}
onkeypress="return checkname(event);
Text Area Max length validation
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
if(ref == 'address') {
if(value.length>100){
if(charCode==8) {
return true;
}
return false;
}
}
}
onkeypress="return count1(value,event,'address')"
Text field Enter key submit Restriction Validation
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
Url, Email Validation
function validate() {
var url=document.getElementById("url").value;
if(url=='') {
alert("url should nt be empty");
}else {
var v = new RegExp();
v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
if (!v.test(url)) {
alert("wrong url");
}else{
alert("url ok");}
}
}
Email Validation:function validate(){
var email=document.getElementById('email').value;
if(email=='') {
alert('email should nt be empty');
}else {
var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
alert('wrong email');
}else{
alert('Email ok');}
}
}
database normalization basics
Normalization is the process of organizing data in a database. This includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.
Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in exactly the same way in all locations. A customer address change is much easier to implement if that data is stored only in the Customers table and nowhere else in the database.
What is an "inconsistent dependency"? While it is intuitive for a user to look in the Customers table for the address of a particular customer, it may not make sense to look there for the salary of the employee who calls on that customer. The employee's salary is related to, or dependent on, the employee and thus should be moved to the Employees table. Inconsistent dependencies can make data difficult to access because the path to find the data may be missing or broken.
There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form." If the first three rules are observed, the database is considered to be in "third normal form." Although other levels of normalization are possible, third normal form is considered the highest level necessary for most applications.
As with many formal rules and specifications, real world scenarios do not always allow for perfect compliance. In general, normalization requires additional tables and some customers find this cumbersome. If you decide to violate one of the first three rules of normalization, make sure that your application anticipates any problems that could occur, such as redundant data and inconsistent dependencies.
The following descriptions include examples.
First Normal Form
- Eliminate repeating groups in individual tables.
- Create a separate table for each set of related data.
- Identify each set of related data with a primary key.
Do not use multiple fields in a single table to store similar data. For example, to track an inventory item that may come from two possible sources, an inventory record may contain fields for Vendor Code 1 and Vendor Code 2.
What happens when you add a third vendor? Adding a field is not the answer; it requires program and table modifications and does not smoothly accommodate a dynamic number of vendors. Instead, place all vendor information in a separate table called Vendors, then link inventory to vendors with an item number key, or vendors to inventory with a vendor code key.
Second Normal Form
- Create separate tables for sets of values that apply to multiple records.
- Relate these tables with a foreign key.
Records should not depend on anything other than a table's primary key (a compound key, if necessary). For example, consider a customer's address in an accounting system. The address is needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead of storing the customer's address as a separate entry in each of these tables, store it in one place, either in the Customers table or in a separate Addresses table.
Third Normal Form
- Eliminate fields that do not depend on the key.
Values in a record that are not part of that record's key do not belong in the table. In general, any time the contents of a group of fields may apply to more than a single record in the table, consider placing those fields in a separate table.
For example, in an Employee Recruitment table, a candidate's university name and address may be included. But you need a complete list of universities for group mailings. If university information is stored in the Candidates table, there is no way to list universities with no current candidates. Create a separate Universities table and link it to the Candidates table with a university code key.
EXCEPTION: Adhering to the third normal form, while theoretically desirable, is not always practical. If you have a Customers table and you want to eliminate all possible interfield dependencies, you must create separate tables for cities, ZIP codes, sales representatives, customer classes, and any other factor that may be duplicated in multiple records. In theory, normalization is worth pursing. However, many small tables may degrade performance or exceed open file and memory capacities.
It may be more feasible to apply third normal form only to data that changes frequently. If some dependent fields remain, design your application to require the user to verify all related fields when any one is changed.
Other Normalization Forms
Fourth normal form, also called Boyce Codd Normal Form (BCNF), and fifth normal form do exist, but are rarely considered in practical design. Disregarding these rules may result in less than perfect database design, but should not affect functionality.
Normalizing an Example Table
These steps demonstrate the process of normalizing a fictitious student table.
- Unnormalized table:
Collapse this tableExpand this tableStudent# Advisor Adv-Room Class1 Class2 Class3 1022 Jones 412 101-07 143-01 159-02 4123 Smith 216 201-01 211-02 214-01 - First Normal Form: No Repeating Groups
Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and Class3 in the above records are indications of design trouble.
Spreadsheets often use the third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below:
Collapse this tableExpand this tableStudent# Advisor Adv-Room Class# 1022 Jones 412 101-07 1022 Jones 412 143-01 1022 Jones 412 159-02 4123 Smith 216 201-01 4123 Smith 216 211-02 4123 Smith 216 214-01 - Second Normal Form: Eliminate Redundant Data
Note the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this relationship is not in second normal form.
The following two tables demonstrate second normal form:
Students:
Collapse this tableExpand this tableStudent# Advisor Adv-Room 1022 Jones 412 4123 Smith 216
Registration:
Collapse this tableExpand this tableStudent# Class# 1022 101-07 1022 143-01 1022 159-02 4123 201-01 4123 211-02 4123 214-01 - Third Normal Form: Eliminate Data Not Dependent On Key
In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below:
Students:
Collapse this tableExpand this tableStudent# Advisor 1022 Jones 4123 Smith
Faculty:
Collapse this tableExpand this tableName Room Dept Jones 412 42 Smith 216 42
Numeric Validation
var charCode = (evt.which != undefined) ? evt.which : evt.keyCode;
if((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 46)
return true;
return false;
}
onkeypress="return NumericKeyEvent(event);