Kishan
Kishan

Reputation: 31

I can't dynamically access a textarea's content with document.getElementById with plain JavaScript

So I have this JSON format

"questionList": [
    {
        "questionText": "Create a function that adds 2 parameters",
        "questionId": "1",
        "testCase": "3,5"
    },
    {
        "questionText": "Write a function that takes two integers, and subtracts the second from the first.",
        "questionId": "12",
        "testCase": "10,3"
    },...
]

I'm dynamically creating textareas where I can answer each question. Here's my code for that

var questionsDiv = document.getElementById("questions");
for (let i = 0; i < questions.length; i++) {
  var div = document.createElement('div');
  div.className = 'question';
  div.innerHTML = '<h3>Question ' + parseInt(i+1) + '</h3><h5>' + questions[i].questionText + '</h5><textarea rows="10" cols="130" id="questionText"' + questions[i].questionId + ' placeholder="Enter your answer here..."></textarea><br><br>'

  questionsDiv.appendChild(div);
}

The end-goal is to create a json with the answer inputted for each question. However, when I try to get the text in the textarea for each one, I get a "cannot read property 'value' of null. These are just some of my attempts at getting the value of questionID 12.

console.log(document.question.questionText+questions[2].questionID.value);
console.log(document.getElementById("questionText12").innerHTML.value);
console.log(document.getElementById("questionText12").value);

How can I dynamically get each value of the textareas with plain JS?

Upvotes: 1

Views: 53

Answers (2)

Icepickle
Icepickle

Reputation: 12806

Well there are a couple of problems, one of which is a double quote that closes the value for your id before you are adding the nr

<textarea rows="10" cols="130" id="questionText' + questions[i].questionId + '" placeholder="Enter your answer here..."></textarea>
//                                             ^ removed " here; added here   ^

Afterwards, you can get the question through

document.getElementById('questionText12')

What you cannot do however, is the following

console.log(document.question.questionText+questions[2].questionID.value);

This will not bring you anything as it would be a string concatenation. In essence it will probably throw an error. If you need to get a property from an object, using calculation, you can always wrap your calculation with obj['questionText' + 12], however I don't think that the property you have in mind exists.

Upvotes: 1

Anthropic
Anthropic

Reputation: 701

I think you have misplaced a double quote:
id="questionText"' + questions[i].questionId + '
should be
id="questionText' + questions[i].questionId + '"
or all your questions will have the same Id.

Upvotes: 1

Related Questions