IamCalvinBrown.com a Blog Site

Code Examples, Consulting Advice and lots of other cool things

Generate a Random name from an array using JQuery


We have an array of items, and we want to pull the item out of the array by id. In this case, the id is randomly generated. If found, show the name.

1. There should be a div somewhere in the body of the screen named message_div

2. 

<script type="text/javascript">

$( document ).ready(function() {

var array = [ 

{'id':'1' ,'name':'IamCalvinBrown'} , 

{'id':'2' ,'name':'Calvin'}, 

{'id':'3' ,'name':'Nailah'}, 

{'id':'4' ,'name':'Kendi'},

{'id':'5' ,'name':'Everybody'}, 

];


$("#changeTextButton").click(function ()

{

// generate a random number between 1 and 5 (change the 5 to increase with the size of the array)

var _randomNumber = Math.floor((Math.random() * 5) + 1);

// find the specific item in our list

// findById takes the array from above and the randomNumber generated

$("#message_div").html(findById(array,_randomNumber));

});


function findById(source, id) {

 var _id = id.toString(); // conver the number to text since we are generating random numbers

 

 for (var i = 0; i < source.length; i++) {

if (source[i].id === _id) {

 return source[i].name;

}

 }

 throw "Couldn't find object with id: " + id;

}

});

</script>

  • Kelly Ford

    9/24/2018 4:51:06 AM |

    Regardless of how frequently I read it, it never gets old. You certainly hit the nail on the head on this one. This is something individuals need to think about. Your blog is really mind blowing and the design is really first class. Really, your blog is mind boggling. It’s important that they know how the structure of online blogs workout. For any kind of help in writing dissertation visit https://dissertationpanda.com

  • zTtaCeKjYg

    8/15/2019 12:31:53 PM |

    324888 762377I recognize there is a superb deal of spam on this internet site.  Do you need to have aid cleaning them up?  I could support in between courses! 436881

Loading