RSS

Category Archives: Javascript

Clone row using javascript

Create element and add that in to table row using javascript.

Create Element Syntax: 

document.createElement(nodename)

Create Element Example:

var txtNode=document.createTextNode(“Hello World”);
var head1=document.createElement(“H1”);
var para=document.createElement(“p”);
var text=document.createElement(‘input’);
var textarea=document.createElement(“textarea”);
var label=document.createElement(‘label’);

Example HTML table Clone:

<body>
 <table id="exampleDataTable" cellpadding="0" cellspacing="0" width="100%" border="0"></table>
<br/>
 <input type="button" id="" onclick="getData('exampleDataTable')" value="submit" />
</body>

Java script methods:

<script type="text/javascript">

 //initially create new table
 addRow('exampleDataTable');
 //delete table row delete button
 function tableDeleteRow(tabObj) {
    var rowsIndex=tabObj.parentElement.parentElement.rowIndex;
    var table = document.getElementById('exampleDataTable');
    try {
       if(rowsIndex!=0){
          table.deleteRow(rowsIndex); 
       }
    }catch(e) {
       alert(e);
    }
 }
 //add table row using add button
 function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    var cell1 = row.insertCell(0);
    var element1 = document.createElement("select");
    cell1.style.padding="3px";
    element1.style.width = "200px";
    element1.style.marginBottom = "0px";
    element1.id="option_example";
    var element1_relation =["Option1","Option2","Option3"];

    for (var i=0;i<element1_relation.length;i++){
       var option;
       option = document.createElement("option");
       option.setAttribute("value", element1_relation[i]);
       option.innerHTML = element1_relation[i];
       element1.appendChild(option);
    }
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement('input');
    cell2.style.padding="3px";
    element2.style.width = "200px";
    element2.style.marginBottom = "0px";
    element2.id="input_example";
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement("textarea");
    cell3.style.padding="3px";
    element3.style.width = "200px";
    element3.style.marginBottom = "0px";
    element3.id="textarea_example";
    cell3.appendChild(element3);

    var cell4 = row.insertCell(3);
    var element4 = document.createElement("BUTTON");
    cell4.style.padding="3px";
    element4.appendChild(document.createTextNode("Add"));
    element4.setAttribute("onClick", "addRow('exampleDataTable')");
    cell4.appendChild(element4);

    var cell5 = row.insertCell(4);
    var element5 = document.createElement("BUTTON");
    cell5.style.padding="3px";
    element5.appendChild(document.createTextNode("Delete"));
    element5.setAttribute("onClick", "tableDeleteRow(this)");
    cell5.appendChild(element5);
 }

 //get all the row data
 function getData(tableID){
    try {
       var table = document.getElementById(tableID);
       var rowCount = table.rows.length;
       var jsonArray = new Array();
       for(var index=0; index < rowCount; index++) {
          var mapObj = {};
          var row = table.rows[index];
          var name1 = row.cells[0].childNodes[0];
          var name2 = row.cells[1].childNodes[0];
          var name3 = row.cells[2].childNodes[0];

          mapObj['name1'] = name1.value;
          mapObj['name2'] = name2.value;
          mapObj['name3'] = name3.value;
      }
    }catch(e) {
       alert(e);
    }
 }

</script>

 

 
3 Comments

Posted by on September 20, 2013 in General, Javascript

 

Tags: ,

Replace Input HTML tags

Replace input html tag to span tag using javascript recursion function. “getFormchildren(startNode,output)” method contain startNode and output div.

Following methods replace tag and its child tag upto end child tag using recursion. We can differentiate value field,non value field, checkbox, radio button, and textarea.

function getFormChildren(startNode, output){
     var nodes;
     if(startNode.childNodes){
          nodes = startNode.childNodes;
          childrenNode(nodes, output);
     }else{
          alert("The Doesnot Have any Child");
     }
}
function childrenNode(nodes, output){
     var node;
     for(var i=0;i<nodes.length;i++){
          node = nodes[i];
          if(output){
               childNode(node);
          }
          if(node.childNodes){
               getFormChildren(node, output);
          }
     }
}
function childNode(node){
 var isCheckBoxChecked = 0;
 var isRadioChecked = 0;
 if(node.nodeType == 1){
 if((node.getAttribute('value') == null || node.getAttribute('value') == "") || (node.id == null || node.id == "")){
 if((node.tagName == 'INPUT' || node.tagName == 'input')&&(node.type != "radio" || node.type != "RADIO")&& (node.type != "checkbox" || node.type != "CHECKBOX")){ 
 $('input[type=button]').each(function(){
 $(this).remove();
 });
 $('input[type=submit]').each(function(){
 $(this).remove();
 }); 
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onClick'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onFocus'));
 htmlSourceViewObj.setAttribute("class",node.getAttribute('class'));
 var value=document.createTextNode(node.value);
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }else if(node.id == null || node.id == "") {

 }else if(node.tagName == "SELECT" || node.tagName == 'select'){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onClick'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onFocus'));
 htmlSourceViewObj.setAttribute("class",node.getAttribute('class'));
 var value=document.createTextNode(node.value);
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }else if((node.tagName == 'textarea' || node.tagName == 'TEXTAREA')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onClick'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onFocus'));
 htmlSourceViewObj.setAttribute("class",node.getAttribute('class'));
 var value=document.createTextNode(node.value);
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }else if((node.tagName == 'img' || node.tagName == 'IMG')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.name);
 htmlSourceViewObj.setAttribute("src",node.getAttribute('src'));
 htmlSourceViewObj.setAttribute("gridName",node.getAttribute('gridName'));
 htmlSourceViewObj.setAttribute("height",node.getAttribute('height'));
 htmlSourceViewObj.setAttribute("width",node.getAttribute('width'));
 var value=document.createTextNode(node.getAttribute('src'));
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }else{

 }
 }else{
 if((node.tagName == 'INPUT' || node.tagName == 'input')&&(node.type == "checkbox" || node.type == "CHECKBOX")){ 
 if(isCheckBoxChecked == 0){
 $('input[type=checkbox]').each(function(){
 if($(this).is(':checked')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",this.id);
 htmlSourceViewObj.setAttribute("name",this.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",this.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("class",this.getAttribute('class'));
 var value=document.createTextNode("True ");
 htmlSourceViewObj.appendChild(value);
 $(this).replaceWith(htmlSourceViewObj);
 }
 if ($(this).is(':not(:checked)')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",this.id);
 htmlSourceViewObj.setAttribute("name",this.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",this.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("class",this.getAttribute('class'));
 var value=document.createTextNode("False ");
 htmlSourceViewObj.appendChild(value);
 $(this).replaceWith(htmlSourceViewObj);
 }
 });
 isCheckBoxChecked = 1;
 } 
 }else if((node.tagName == 'INPUT' || node.tagName == 'input')&&(node.type == "radio" || node.type == "RADIO")){
 if(isRadioChecked == 0){
 $('input[type=radio]').each(function(){
 if($(this).is(':checked')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",this.id);
 htmlSourceViewObj.setAttribute("name",this.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",this.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("class",this.getAttribute('class'));
 var value=document.createTextNode("True ");
 htmlSourceViewObj.appendChild(value);
 $(this).replaceWith(htmlSourceViewObj);
 }
 if ($(this).is(':not(:checked)')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",this.id);
 htmlSourceViewObj.setAttribute("name",this.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",this.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("class",this.getAttribute('class'));
 var value=document.createTextNode("False ");
 htmlSourceViewObj.appendChild(value);
 $(this).replaceWith(htmlSourceViewObj);
 }
 });
 isRadioChecked = 1;
 } 
 }else if((node.tagName == 'INPUT' || node.tagName == 'input')&&(node.type != "radio" || node.type != "RADIO")&& (node.type != "checkbox" || node.type != "CHECKBOX")){
 $('input[type=button]').each(function(){
 $(this).remove();
 });
 $('input[type=submit]').each(function(){
 $(this).remove();
 });
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.getAttribute('name'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onchange'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onClick'));
 htmlSourceViewObj.setAttribute("onchange",node.getAttribute('onFocus'));
 htmlSourceViewObj.setAttribute("class",node.getAttribute('class'));
 var value=document.createTextNode(node.getAttribute('value'));
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }else if((node.tagName == 'img' || node.tagName == 'IMG')){
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.name);
 htmlSourceViewObj.setAttribute("src",node.getAttribute('src'));
 htmlSourceViewObj.setAttribute("gridName",node.getAttribute('gridName'));
 htmlSourceViewObj.setAttribute("height",node.getAttribute('height'));
 htmlSourceViewObj.setAttribute("width",node.getAttribute('width'));
 var value=document.createTextNode(node.getAttribute('src'));
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }else{
 var htmlSourceViewObj = document.createElement("span");
 htmlSourceViewObj.setAttribute("id",node.id);
 htmlSourceViewObj.setAttribute("name",node.getAttribute('name'));
 htmlSourceViewObj.setAttribute("class",node.getAttribute('class'));
 var value=document.createTextNode(node.value);
 htmlSourceViewObj.appendChild(value);
 $("#"+node.id).replaceWith(htmlSourceViewObj);
 }
 }
 } 
}
 
Leave a comment

Posted by on September 20, 2013 in General, Javascript, jquery

 

Tags: , , ,

Clone html table using jquery

Clone table content and set count value in attribute using jquery.

<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
/*Global count to set the attribute id*/
var count= 1;

/*Clone row using the table name*/
function addCloneMappingRow(id){
   var table = document.getElementById( id );
   if ( table ) {
     var tbody = table.getElementsByTagName('tbody')[ 0 ];
     var numRows = tbody.rows.length;
     var lastRow = tbody.rows[ numRows - 1 ];
     var newRow = lastRow.cloneNode( true );
     var rowid='row' + numRows;
     newRow.setAttribute( 'id', 'row' + numRows );
     $(newRow).find('input, hidden, select, textarea, checkbox').each(function(){
      var currentNameAttr = $(this).attr('name'); 
      // get the current name attribute
      // construct a new name attribute using regular expressions
      // the match is divided into three groups (indicated by parentheses)
      // p1 will be 'v', p2 will be the number, p3 will be the remainder of the string
     var newNameAttr = currentNameAttr.replace(/([^\d]*)(\d*)([^\w]*)/, function(match, p1, p2, p3) {
        return p1+(count)+p3;
     });
     $(this).attr('name', newNameAttr); 
     if( newNameAttr.indexOf("id") !== -1){
       $(this).attr('value', ''); 
     }else{
     }
    });
    tbody.appendChild( newRow );
 }
 count++;
}

/*delete the row and not allow to remove last one*/
function deleteCloneMappingRow(row){
   if(count <= 1){
     alert("No Privilege to Remove");
     return false;
   }else{
     var parentNode=row.parentNode.parentNode.parentNode;
     $(parentNode).find('input, hidden, select, textarea, checkbox').each(function(){
     var currentNameAttr = $(this).attr('name'); // get the current name attribute
     if( currentNameAttr.indexOf("id") !== -1){
       var val = $(this).attr('value');
       if (val) {
         var deletingrowval = $('#deletingRows').val();
         $('#deletingRows').val(deletingrowval+","+val);
       }
     }
   });
   var delRow=row.parentNode.parentNode.parentNode.rowIndex;
   document.getElementById('cloneTable').deleteRow(delRow);
   count--;
  }
 }
</script>
</head>
<body>
<table id="cloneTable">
 <tr id="row0">
 <td><input type='text' id='name' name='name'></td>
 <td><input type='text' id='id' name='id'></td>
 <td><input type='text' id='last' name='last'></td>
 <td><textarea id='address' name='address' cols='20' rows='3'></textarea></td>
 <td><a href="#" onclick="addCloneMappingRow('cloneTable')" >Add</a></td>
 <td><a href="#" onclick="deleteCloneMappingRow(this)" >Delete</a></td>
 </tr>
</table>
</body>
</html>
 
Leave a comment

Posted by on April 19, 2013 in General, Javascript, jquery

 

Tags: , , ,

Parse html and get / set attribute values

Parse the html using javascript and get the attribute values.

<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function return_MemOfIdByTag(a,b){
 return jQuery(b,jQuery(a));
}
function parseHtml(){
 var htmlString = document.getElementById('parseTest').innerHTML;
 var editorObj = document.createElement('div');
 editorObj.innerHTML = htmlString;
 var input_tags=return_MemOfIdByTag(editorObj,'input');
 if(input_tags.length > 0){
    for(var index = 0; index < input_tags.length; index++){
      var type = input_tags[index].getAttribute('type');
      var name = input_tags[index].getAttribute('name');
      var id = input_tags[index].getAttribute('id');
      document.getElementById(id).setAttribute('value','testValue');
      document.getElementById(id).setAttribute('table','tableValue');
     document.getElementById(id).setAttribute('column','columnValue');
   }
 }

 var select_tags=return_MemOfIdByTag(editorObj,'select');
 if(select_tags.length > 0){
   for(var index = 0; index < select_tags.length; index++){
     var type = select_tags[index].getAttribute('type');
     var name = select_tags[index].getAttribute('name');
     var id = select_tags[index].getAttribute('id');
     document.getElementById(id).setAttribute('value','testValue');
     document.getElementById(id).setAttribute('table','tableValue');
     document.getElementById(id).setAttribute('column','columnValue');
   }
 }
 var ta_tags=return_MemOfIdByTag(editorObj,'textarea');
 if(ta_tags.length > 0){
   for(var index = 0; index < ta_tags.length; index++){
     var type = ta_tags[index].getAttribute('type');
     var name = ta_tags[index].getAttribute('name');
     var id = ta_tags[index].getAttribute('id');
     document.getElementById(id).setAttribute('value','testValue');
     document.getElementById(id).setAttribute('table','tableValue');
     document.getElementById(id).setAttribute('column','columnValue');
   }
 }
}
</script>
</head>
<body>
<div id="parseTest">
 <input type='text' id='name' name='name'>
 <input type='text' id='id' name='id'>
 <input type='text' id='last' name='last'>
 <textarea id='address' name='address' cols='20' rows='3'></textarea>
</div>
<input type="button" onclick="parseHtml()" value="click"/>
</body>
</html>
 
Leave a comment

Posted by on April 19, 2013 in Javascript, jquery, Strings

 

Tags: , , ,

String operations in javascript

Find last two character in string:

var chrStr = "find last two character";
var last2 = chrStr.slice(-2);
(OR)
var last2 = chrStr.substr(chrStr.length-2);
alert(last2); // "er"

Remove last 2 character in string:

var str = "remove last two character";
str = str.substring(0, str.length - 2);
alert(Str); // remove last two charact
 
Leave a comment

Posted by on April 11, 2013 in Javascript

 

Tags: , ,

How to get/set element attribute value in javascript

The .setAttribute(‘attributeName’,’content’) method is used to set content to the attribute and .getAttribute(‘atrributeName’)  method is used to get attribute value.

Example:

<!DOCTYPE html>
<html>
<head>
<meta id="description" name="description" 
content="Free Web tutorials" />
<meta name="keywords" content="HTML,CSS,XML,JavaScript" />
<meta name="author" content="Hege Refsnes" />
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script type="text/javascript">
function setProductMeta(){
document.getElementById("description")
                          .setAttribute("content","testdesc");
var metaDesc=document.getElementById("description")
                                     .getAttribute("content");
document.getElementById("attr-test")
                           .setAttribute("value","testvalue");
var textValue = document.getElementById("attr-test")
                                       .getAttribute("value");
}
</script>
</head>
<body>
 <a href="#" onclick="setProductMeta()" >Click set&get Attribute</a>
 <input type="text" name="attribute-test" id="attr-test" value="" />
</body>
</html>
 
Leave a comment

Posted by on December 13, 2012 in General, Javascript

 

Tags: , , ,

How to get elements by name in javascript

The getElementsByName() method is used to get the element by name. However be aware of the getElementsByName() method always return an array.

Example:

<!DOCTYPE html>
<html>
<head>
 <script type="text/javascript">
 function getElements(){
 var x=document.getElementsByName("x");
 for(var i=0;i<x.length;i++){
 alert(x[i].value);
 }
 }
 </script>
</head>
<body>
 Cats: <input name="x" type="radio" value="Cats" />
 Dogs: <input name="x" type="radio" value="Dogs" />
<input type="button" onclick="getElements()" 
value="clickToGetByName"/>
</body>
</html>

There are no getElementByName() exists, Its getElementsByName().

 
Leave a comment

Posted by on December 13, 2012 in General, Javascript

 

Tags: , ,

Using javascript Attribute to set meta tags dynamically

Set meta tags content dynamically using javascript setAttribute.

Example for setAttribute : 

<meta id="description" name="description" 
content="example meta description content" />
<meta name="keywords" content="example meta keywords content" />
<meta name="author" content="example author conent" />
<title>example title content</title>
<script type="text/javascript">
 window.onload = function () {
     setProductMeta();
 }
function setProductMeta(){
 document.getElementById("description").setAttribute("content",
"dynamic meta description");
 document.getElementById("keywords").setAttribute("content",
"dynamic meta description");
 document.title = 'dynamic meta title';
}
</script>

Example for getAttribute : 

<meta id="description" name="description" 
content="example meta description content" />
<meta name="keywords" content="example meta keywords content" />
<meta name="author" content="example author conent" />
<script type="text/javascript">
window.onload = function () {
 setProductMeta();
}
function setProductMeta(){
 var metaDesc = document.getElementById("description")
.getAttribute("content");
 var metaKeys = document.getElementById("keywords")
.getAttribute("content");
 var metaAuthor = document.getElementById("author").getAttribute("content"); 
 document.getElementById("demoDesc").innerHTML= metaDesc;
 document.getElementById("demoKeys").innerHTML= metaKeys;
 document.getElementById("demoAuthor").innerHTML= metaAuthor;
}
</script>
<div id="demoDesc"></div>
<div id="demoKeys"></div>
<div id="demoAuthor"></div>
 
6 Comments

Posted by on July 26, 2012 in General, Javascript

 

Tags:

Countdown timer in javascript

Just provide expiry date and time in the script.

Example: var exp = montharray[Month – 1] + ” ” + Day + “, ” + Year + ” ” + Hour + “:” + Minute + “:” + Second;

After expired, It will show the alert “Time expiry.”,  Insted of timer it will show the text “The time has come!”

<html>
<body>
<div id="countdown_time"></div>
<script type="text/javascript">
var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun"
,"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
window.onload=function(){ 
updateTime();
}
function updateTime() {
today = new Date();
var todayy = today.getYear();
if (todayy < 1000)
todayy += 1900;
var curr = montharray[today.getMonth()] + " " + today.getDate()
+ ", " + todayy + " " + today.getHours() + ":"
+ today.getMinutes() + ":" + today.getSeconds();
var exp = montharray[7 - 1] + " " + 10 + ", " + 2012 + " " + 18 
+ ":" + 14 + ":" + 00;
timeLeft = Date.parse(exp) - Date.parse(curr);
msPerDay = 24 * 60 * 60 * 1000;
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft) * 24;
hrsLeft = Math.floor(e_hrsLeft);
e_minsLeft = (e_hrsLeft - hrsLeft) * 60;
minsLeft = Math.floor(e_minsLeft);
scesLeft = Math.floor((e_minsLeft - minsLeft) * 60);
document.getElementById("countdown_time").innerHTML = "<table "
+"border=0 width='160px'><tr><td align='right'>"
+ daysLeft
+ "</td><td align='left' colsapn='2'>Days</td> <td align='right'>"
+ hrsLeft
+ "</td><td align='left' colsapn='2'>Hours</td><td align='right'>"
+ minsLeft
+ "</td><td align='left' colsapn='2'>Mins</td><td align='right'>"
+ scesLeft
+ "</td><td align='left' colsapn='2'>Secs</td></tr></tbody></table>";
if (timeLeft > 1000) {
setTimeout('updateTime()', 1000);
} else {
alert("Time expiary.");
document.getElementById("countdown_time").innerHTML =
"The time has come!";
}
}
</script>
</body>
</html>
 
Leave a comment

Posted by on July 11, 2012 in General, Javascript

 

Tags: , ,

Remove Array element by Index / Value

Remove Array element by Index:

First we will see an example were we will remove array element by its index. For this we can define a generic function removeByIndex().

function removeByIndex(arr, index) {
    arr.splice(index, 1);
}

In above code we used javascript splice() method to remove element at an index. splice() method takes two argument. First is the index at which you want to remove element and second is number of elements to be removed. In our case it is 1.

To test the above code lets define a simple array and remove one of the element.

Example:

test = new Array();
test[0] = 'Arjun';
test[1] = 'Bala';
test[2] = 'Charu';
test[3] = 'Danush';
alert("Array before removing elements: "+test);
removeByIndex(test, 2);
alert("Array after removing elements: "+test);

Also you may want to define removeByIndex method with an array so that you call it directly. For example, in following example, we have define an array test and its method removeByIndex().

Example:

test = new Array();
//define removeByIndex method as part of the array
Array.prototype.removeByIndex = function(index) {
    this.splice(index, 1);
}
test[0] = 'Arjun';
test[1] = 'Bala';
test[2] = 'Charu';
test[3] = 'Danush';
alert("Array before removing elements: "+test);
test.removeByIndex(2);
alert("Array after removing elements: "+test);

Remove Array element by Value:

You may want to remove array element by its value and not index. This can be easily done by iterating through it and comparing the values, if a match is found we can remove that element by splice() method.

function removeByValue(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}

The above code can be written as part of array also:

Example:

test = new Array();
Array.prototype.removeByValue = function(val) {
    for(var i=0; i<this.length; i++) {
        if(this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}
test[0] = 'Arjun';
test[1] = 'Bala';
test[2] = 'Charu';
test[3] = 'Danush';
alert("Array before removing elements: "+test);
test.removeByValue('Cat');
alert("Array after removing elements: "+test);
 
Leave a comment

Posted by on July 4, 2012 in General, Javascript

 

Tags: ,