saif maher
saif maher

Reputation: 7

how i can print letter user clicked in javascript?

welcome

I need to show an alert box when the user clicks each button in my code

Example: User clicks H Button .. alert must show H letter

This is the code

  var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];

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


  function printchar()

      alert("here how i can print the letter i was clicked ?")



    document.write("<div>");
    for(var j = 0; j < key[i].length; j++)

       document.write("<input type='button' onclick='printchar()' value='" + key[i][j] + "'/>");

    document.write("</div>");

Upvotes: 0

Views: 561

Answers (3)

JDB
JDB

Reputation: 25810

If you don't want to completely re-engineer your solution (which is missing a bunch of curly braces, by the way), you could just pass the letter in as an argument to your printchar function...

for(var j = 0; j < key[i].length; j++){
    document.write("<input type='button' onclick='printchar(\"" + key[i][j] + "\")' value='" + key[i][j] + "'/>");
}

function printchar(letter){
    alert(letter);
}

Alternately, you can use events and closures to avoid inserting javascript into your HTML string:

key[i].forEach(function(currentKey){
    var btn = document.createElement('input');
    btn.value = currentKey;
    btn.onclick = function(){
        alert(currentKey);
    }
    // ... now insert btn somewhere on the page
});

Upvotes: 1

freginold
freginold

Reputation: 3956

Here is a working solution using your code, plus a couple of changes:

  var key = [["q","w","e","r","t","y","u","i","o","p"],["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];

  function printchar(letter) {
      alert(letter);
  }

  for(var i = 0; i < key.length; i++) {
    document.write("<div>");
    for(var j = 0; j < key[i].length; j++) {
       document.write("<input type='button' onclick='printchar(this.value);' value='" + key[i][j] + "'/>");
       document.write("</div>");
    }
  }

The changes include:

  • adding braces ({ and }) around the printchar function and the for loops
  • passing the value of the selected button into the printchar function (as letter)

Upvotes: 1

Sagar V
Sagar V

Reputation: 12478

A short method is there use forEach to iterate through the array and create button, add onclick to every newly created button.

var keys=['A','B','Z'];
keys.forEach(function(key){
    var btn=document.createElement('button');
    btn.onclick=function(){alert(this.innerHTML);};
   btn.innerHTML=key;
   document.body.appendChild(btn);
 });

Upvotes: 2

Related Questions