Reputation: 57
I have a javascript page (function.js) that is included in my game.php and within functions.js is defined an array. Like this:
var palavra=[];
function fun(){
var input=document.getElementById("palavra").value;
var letra1=input.charAt(0);
var letra2=input.charAt(1);
var letra3=input.charAt(2);
var letra4=input.charAt(3);
var letra5=input.charAt(4);
letra1=palavra[0];
letra2=palavra[1];
letra3=palavra[2];
letra4=palavra[3];
letra5=palavra[4];
}
This function is triggered by an onclick event in the game.php page:
<input id="palavra" type="text" name="palavra" maxlength="5">
<button onclick="fun()" id="btn"> Enviar</button>
I want each index of the array to show in the middle of html tag like show bellow (also in the game.php)
<span class="letra"><script> palavra[0]</script></span>
<span class="letra"><script> palavra[1]</script></span>
<span class="letra"><script> palavra[2]</script></span>
<span class="letra"><script> palavra[3]</script></span>
<span class="letra"><script> palavra[4]</script></span>
However, when I click on the button nothing happens and I have the following errors:
Uncaught ReferenceError: palavra is not defined at game.php
Uncaught ReferenceError: fun is not defined at HTMLButtonElement.onclick (game.php)
I don't understand why this is happening, can someone tell me where the problem is.
Upvotes: 1
Views: 56
Reputation: 50664
It's not entirely clear what you're trying to do, however, from what I understand, you can achieve what you want to achieve by using a for-in
loop to get every character in your input. Then instead of using HTML to input each letter, you use javascript by doing document.body.innerHTML
to append each letter/character to your document.
See working example below:
function fun() {
var input = document.getElementById("palavra").value;
for (i in input) {
document.body.innerHTML += '<br /><span class="letra">' + input[i] + '</span>';
}
}
<input id="palavra" type="text" name="palavra" maxlength="5" />
<button onclick="fun()" id="btn"> Enviar</button>
<!-- This will be generated using javascript-->
<!--span class="letra"><script> palavra[0]</script></span>
<span class="letra"><script> palavra[1]</script></span>
<span class="letra"><script> palavra[2]</script></span>
<span class="letra"><script> palavra[3]</script></span>
<span class="letra"><script> palavra[4]</script></span-->
Upvotes: 1