Search code examples
javascriptdomtextboxfield

How can I input a character inside a DOM Field Object at a particular index?


Basically, I'm trying to input a letter inside a field object at a particular index. This is for a simple hangman game. I initialized that field object as an array variable. However, whenever i try to input a character value (stored as a variable), it doesn't show up inside the field. I tried everything I could think of but nothing is working.

To create a new field each time, I used the "createElement("INPUT")" method. This element is initialized as an array variable. Then, I tried numerous options to enter a particular letter inside that field object at a certain index. It's not working.

//This is the code to create the new Field Object:

     var inputField = [];
    for(var i = 0; i<fruitLength; i++ ){

        inputField = document.createElement("INPUT");

        document.getElementById("textBox").appendChild(inputField);

    }
//Below is the snippet of code where Im trying numerous options to enter inside a particular field:  Ex, letterIndex = 2.

    var letter = "E"
    if(letterIndex != -1){
        //document.forms[0].elements[0].innerHTML = letter;
        //var s = $('#textBox`enter code here`').val();
        inputField[letterIndex].value = letter;
    }

I'm not really getting errors, but Im not getting what I expected.


Solution

  • Here is one error :

    var inputField = [];
    for(var i = 0; i<fruitLength; i++ ) {
       // ERROR : variable inputField will be replace
       // inputField = document.createElement("INPUT");
    
       // Should be something like
       inputField[i] = document.createElement("INPUT");
    }