Search code examples
javascriptangularjsmultidimensional-arrayindexofwordsearch

Capturing index of an array onclick with JavaScript


https://jsbin.com/zesegigego/edit?html,js,output

I'm creating a word search puzzle and at the point where I want to implement functionality to allow the users to mark the words they find. I have an array of s which contain randomly generated letters and letters to the words to be found. The s of the words to be found have a class="answerLetter", but I am having trouble capturing each index at a time to tell my JavaScript to change do something with those specific indexes I click on. I apologize if there is lack of clarity, but the jsbin link is above to view what I have so far.

I know how to do this with AngularJs where an ng-repeat can be "track by $index" and I just bring that specific index from the HTML to my controller by inserting the $index in the parenthesis of the function like so ng-click="selectThisIndex($index)". How do I do this with vanilla JavaScript?

https://jsbin.com/zesegigego/edit?html,js,output

//==============SUBMITTING ANSWERS=======================================

function showSubmit() {
document.getElementById('submitBut').innerHTML = 
'<button onclick="submitLetters()">SUBMIT LETTERS</button>';
var arrayOfTds = document.getElementsByClassName('answerLetter');
console.log(arrayOfTds);
}

//==============CREATING GRID OF RANDOM LETTERS====================

var cols = 20; 
var rows = 10; 
var html = ""; 

for(var i = 0; i <= rows; i++) { 
html += '<tr>'; 
for(var h= 0; h <= cols; h++) { 
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ'; 
    var random = parseInt(Math.random()*characters.length);
    var letter = characters.charAt(random); //returning random letter
    html += '<td onclick="showSubmit()">' + letter + '</td>'; 
} 
html += '</tr>'; 
}

document.getElementById('wsBox').innerHTML += html;

Solution

  • I think this is what you want :)

    <!DOCTYPE html>
    <html>
    
    <head>
      <title>test</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <style>
        .box {
          width: 30px;
          height: 30px;
          margin: 5px;
          float: right;
          background: #eee;
          border: solid 1px #ccc;
          list-style: none;
        }
      </style>
    </head>
    
    <body>
    
      <ul></ul>
    
      <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
      <script>
        for (var i = 0; i < 20; i++) {
          $("ul").append("<li class=\"box\">" + i + "</li>");
        }
    
        $(".box").each(function(index) {
          $(this).click(function() {
            console.log(index);
          });
        });
      </script>
    </body>
    
    </html>