简体   繁体   English

如何从 typescript 中的多个输入字段中获取值?

[英]How to fetch values from multiple input fields in typescript?

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: e.value 的控制台日志是:

NodeList [input.criteria-box]节点列表 [input.criteria-box]

0: input.criteria-box 0:input.criteria-box

length: 1长度: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?关于如何在循环中获取值的任何想法?

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.要修复编译错误,我们需要将HTMLInputElement指定为我们正在迭代的每个元素的类型。

You can use您可以使用

 document.querySelectorAll(".criteria-box");

that should return array of all elements matching class name.criteria-box那应该返回匹配 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.该解决方案将更无错误,并允许您在单个表单中处理数据,而不是在整个网站上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM