Reading a value from a dynamically created button in Javascript / HTML

I created a virtual keyboard and am trying to fill in the input field with the letters that appear on the button. I have the following functions:

This function takes a character and makes it a char button as its value:

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.id = "btn";
  keyStroke()
  return btn;
}

This function creates a button for all letters:

var keyList = "QWERTYUIOPASDFGHJKLZXCVBNM";
for (i in keyList)
{
  var button = keyButton(keyList[i]);
  document.body.appendChild(button)
}

This function is a problem, it should read the value from the button and add it to the input field:

function keyStroke() {
  document.getElementById("searchBar").value += document.getElementById("btn").innerText;
}

The HTML for the input field looks like this:

<input id="searchBar" class="inputBar" placeholder="Enter something" />
+4
source share
3 answers

Try the following:

var keyList = "QWERTYUIOPASDFGHJKLZXCVBNM";

for (var i in keyList) {    //loop through letters in keyList
  var button = keyButton(keyList[i]);
  document.body.appendChild(button);
}

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerHTML = char; //fill it with char
  btn.onclick = function () { keyStroke(this); };
  return btn;
}

function keyStroke(b) {
  document.getElementById("searchBar").value += b.innerHTML;
}
<input id="searchBar" class="inputBar" placeholder="Enter something" />
Run codeHide result
+3
source

if you create an event handler for the button click event where you created it, you can get the button data when the button is clicked

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.id = "btn";
  btn.onclick = function() {//yourcodehere}
  keyStroke()
  return btn;
}

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  btn.id = "btn";
  btn.onclick = keyStroke;
  keyStroke()
  return btn;
}

keyStroke, .

function keyStroke(evt) {
  document.getElementById("searchBar").value += evt.target.innerText;
}
0

find a working solution below:

tagged add button

function keyButton(chara) {
var btn = document.createElement("button"); //create button
btn.innerText = chara; //fill it with char
btn.id = "btn";
btn.onclick=onclickFunction;
return btn;
}

onclick button functions:

function onclickFunction(ev){
var searchBar=document.getElementById('searchBar');
searchBar.value=searchBar.value + ev.srcElement.innerText;
}
0
source

Source: https://habr.com/ru/post/1663525/


All Articles