Pages

Thursday, April 5, 2012

assigning dynamic key name in javascript/jquery object

dynamic key name javascript object

here you can see the live demo and see code there also
live demo url:  http://jsbin.com/edibuk

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

<script>
var curdoctypedata = {};

var map = {
  'key 1 from map': 'val1',
  'key 2 from map': 'val2'
};

//assign dynamic key
$.each(map, function(key, value) {
    curdoctypedata[key] = value ;
});

//display assigned dynamic key name
$.each(curdoctypedata, function(key, value) {
    alert ('key: ' + key + '|||' + 'value: ' +value);
});


</script>

looping Array / structure in javascript OR looping Array / structure in jquery

 looping array/structure in jquery or in javascript. here is simple code from jquery. 


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

<script>
//array
var mykids = new Array();
mykids[0]="kid1";     
mykids[1]="kid2";
mykids[2]="kid3";

$.each(mykids, function(index, value) {
  alert(index + ': ' + value);
});

/structure
var map = {
  'key 1': 'val1',
  'key 2': 'val2'
};
$.each(map, function(key, value) {
  alert(key + ': ' + value);
});

</script>

Monday, April 2, 2012

indexOf is not working in javascript OR searching a item in a list OR searching a item in array in javascript

indexOf is not working in javascript.

//code :  // not wotking
var commonerr = [ 1, 2, 3, 4, 5 , 6 ];     //array              

if (commonerr.indexOf(errorNumber)  != -1){   
// to do 
}


IndexOf is not supported in Internet explorer. Its supported in FF and other browsers.

I found few blogs and its seems like they have a work around for this. You can simply use prototype to extend this method.  please refer below url.
http://www.pearweb.com/javascript/array-index-of.html

2nd way :

Or you can use below code. Jquery has a nice method "inArray" which will help you in searching a item in a array.

here is the link of jquery
http://api.jquery.com/jQuery.inArray/

var commonerr = [ 1, 2, 3, 4, 5 , 6 ];     //array                      
                            
if ( $.inArray(errorNumber, commonerr) != -1){  
//to do
}