I have an assignment as a part of a cyber security course where I am supposed to submit a form with specific values for the inputs.
here is the relevant snippet of the source code I am working with is: (source code for a messaging system)
<div class="form-group">
<label for="inputSubject">Subject:</label>
<input name="subject" type="text" class="form-control" id="inputSubject" placeholder="Enter a subject" pattern=".{5,}" required>
</div>
<div class="form-group">
<textarea name="contents" class="form-control" rows="10" placeholder="Enter your message" pattern=".{5,}" required></textarea>
</div>
whenever I am trying to set the value of the textarea using either getElementsbyName or getElemetnsbyTagName, I get the error "Uncaught TypeError: Cannot set properties of null. Any idea how to fix this?
Two things:
value or textContent.const textArea = document.querySelector('textarea[name="contents"]');
textArea.textContent = `whatever you want it to say`.
As a getElementsByName return a list of nodes and you only have one element with that name:
This should work for you:
document.getElementsByName("contents")[0].value = "hello world"
here how you could implemented:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="form-group">
<label for="inputSubject">Subject:</label>
<input name="subject" type="text" class="form-control" id="inputSubject" placeholder="Enter a subject"
pattern=".{5,}" required>
</div>
<div class="form-group">
<textarea name="contents" class="form-control" rows="10" placeholder="Enter your message" pattern=".{5,}"
required></textarea>
</div>
<script>
document.getElementsByName('contents')[0].value = 'hello world'
</script>
</body>
</html>
Import a script in your html with this way <script defer src="script.js"></script> so that the DOM tree is created. In your imported script, you can do this: document.getElementsByTagName("textarea")[0].value = "Test Value";