We are making a site to play and solve Sudoku. For this we wanted a javascript function running when you press a number. But the onkeypress call is acting weird. It does give the cell number you are changing it in but it doesn't see the input itself on key press, unless you press it twice. (?) Or give enter. How would it properly work both? Also found here: www.patternsinwords.com/sudoku for if you want to try. With kind regards, Jaap
<html>
<head>
<script type="text/javascript">
function myFunction(val) {
var x = document.getElementById(val).value;
document.getElementById("alerts").innerHTML = "You changed " + x + " on cell " + (val+1);
}
</script>
<style>
input[type=text] {
width: 20px;
border: none;
font-size: 20px;
align: center;
}
table{
border-collapse: collapse;
}
div{
align: center;
}
td:nth-child(3) {border-right: 2px solid black;}
td:nth-child(6) {border-right: 2px solid black;}
tr:nth-child(3) {border-bottom: 2px solid black;}
tr:nth-child(6) {border-bottom: 2px solid black;}
</style>
</head>
<body>
<center>
<?php
echo '<br><table border="3"><tr>';
$vertical = 0;
for ($i=0;$i<=80;$i++){
if ($i%9==0 && $i>0){
$vertical++;
echo '</tr><tr>';
}
echo '<td align="center" width="50" height="50"><input type="text" autocomplete="off" maxlength="1" id="'.$i.'" onkeypress="myFunction('.$i.')">';
}
echo '</tr></table>';
echo '<br><div id="alerts"></div>';
?>
</center>
</body>
</html>
You can't get new value from input element because of events order. Keypress event (it's better to use keydown or input event because of keypress is deprecated event) fires before the value set into the input element. Using keypress event you can get only a previously set input value.
To solve the problem you can use 'input' event:
echo '<td align="center" width="50" height="50"><input type="text" autocomplete="off" maxlength="1" id="'.$i.'" oninput="myFunction('.$i.')"></td>';
Another way is to get input value directly from event. In my opinion this is the best way because you don't have to access the DOM to get the value you already have. If you'd prefere to use event based case you should change you function to
function myFunction(e, cellId) {
var key = e.key;
document.getElementById("alerts").innerHTML = "You changed " + key + " on cell " + (cellId+1);
}
and cell markup to
echo '<td align="center" width="50" height="50"><input type="text" autocomplete="off" maxlength="1" id="'.$i.'" onkdown="myFunction(event, '.$i.')"></td>';