I have a few Input fields, which are dynamically generated. I want to fetch the text entered in the input field on a button click.
The console log of e.value is :
NodeList [input.criteria-box]
0: input.criteria-box
length: 1
What is want is to get the value of the input fields.
const criteria_elems = document.getElementsByName('criteria-field');
criteria_elems.forEach((e) => {
console.log(e.value); // Property 'value' does not exist on type 'HTMLElement'.ts(2339)
})
<input type="text" class="criteria-box" name="criteria-field" placeholder="Enter Criteria" required /><br>
<input type="text" class="criteria-box" name="criteria-field" placeholder="Enter Criteria" required /><br>
<input type="text" class="criteria-box" name="criteria-field" placeholder="Enter Criteria" required /><br>
<input type="text" class="criteria-box" name="criteria-field" placeholder="Enter Criteria" required /><br>
<input type="text" class="criteria-box" name="criteria-field" placeholder="Enter Criteria" required />
The input fields gets generated at first, then user can enter data to those fields and click on a button.
At this time the entered data in each of the fields are to be fetched using some loop logic or so. Any ideas on how to fetch value inside the loop?
CodePudding user response:
Ideally, you should be using reactive form group for such tasks. You can create a form array for dynamic input element and then you can easily fetch values from that form array.
Still, to resolve your issue temporally, modify your code like this:
criteria_elems.forEach((e: HTMLInputElement) => {
console.log(e.value);
})
To fix the compilation error, we need to assign the HTMLInputElement
as the type of each of the element that we are iterating over.
CodePudding user response:
You can use
document.querySelectorAll(".criteria-box");
that should return array of all elements matching class name .criteria-box
Otherwise, I'd suggest wrapping all fields into single form tag and process form data on submit event. That solution would be more bug-free and allow you to process data within a single form, not across the entire website.