Thursday, July 3, 2014

Check if Form is Dirty in javascript (You need to check if user changed anything in an HTML form. Below function formIsDirty returns a boolean value true or false depending on weather user modified something within the form.)

1)

/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
 *                   otherwise.
 */
function formIsDirty(form) {
  for (var i = 0; i < form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
    if (type == "checkbox" || type == "radio") {
      if (element.checked != element.defaultChecked) {
        return true;
      }
    }
    else if (type == "hidden" || type == "password" ||
             type == "text" || type == "textarea") {
      if (element.value != element.defaultValue) {
        return true;
      }
    }
    else if (type == "select-one" || type == "select-multiple") {
      for (var j = 0; j < element.options.length; j++) {
        if (element.options[j].selected !=
            element.options[j].defaultSelected) {
          return true;
        }
      }
    }
  }
  return false;
}

2)

window.onbeforeunload = function(e) {
  e = e || window.event; 
  if (formIsDirty(document.forms["someForm"])) {
    // For IE and Firefox
    if (e) {
      e.returnValue = "You have unsaved changes.";
    }
    // For Safari
    return "You have unsaved changes.";
  }
};

Warn user if Back is pressed in javascript

 window.onbeforeunload = function () {
            return "You work will be lost.";
        };

Generate Random number from 1 to N in javascript

//random number from 1 to N
var random = Math.floor(Math.random() * N + 1);

Javascript Function To Remove Array element by Value

function removeByValue(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}
 
var somearray = ["mon", "tue", "wed", "thur"]
 
removeByValue(somearray, "tue");
 
//somearray will now have "mon", "wed", "thur"

Javascript Function To Remove Array element by Index

function removeByIndex(arr, index) {
    arr.splice(index, 1);
}
 
test = new Array();
test[0] = 'Apple';
test[1] = 'Ball';
test[2] = 'Cat';
test[3] = 'Dog';
 
alert("Array before removing elements: "+test);
 
removeByIndex(test, 2);
 
alert("Array after removing elements: "+test);