简体   繁体   English

需要使用 vanilla Javascript 从 HTML 表单中获取数据

[英]Need to get data out of an HTML form using vanilla Javascript

I'm trying to get some simple data out a form on a webpage.我正在尝试从网页上的表单中获取一些简单的数据。 Should be pretty simple, but one, I can't use jQuery, it has to be plain JS, and two, it's on a legacy system so it has to work in IE11 only.应该很简单,但是一,我不能使用 jQuery,它必须是普通的 JS,二,它在一个遗留系统上,所以它只能在 IE11 中工作。

Here is an image of the form fields I'm working with:这是我正在使用的表单字段的图像:

在此处输入图像描述

I need to get the ID of the label and the value of the field as indicated in the red boxes.我需要获取 label 的 ID 和红色框中所示的字段值。 This is how they're mapping this to the DB.这就是他们将其映射到数据库的方式。 I have to pull these on the form, then put them in a spreadsheet.我必须将它们拉到表格上,然后将它们放入电子表格中。

The most simple way I've tried to do this is using:我尝试过的最简单的方法是使用:

document.getElementById('Section1_0').getElementsByTagName('*');

Of course this is kind of overkill since then I get back EVERY node in the DOM and then I would have to parse that out using something like JSON.parse() or something similar.当然,这有点矫枉过正,因为我回到了 DOM 中的每个节点,然后我必须使用JSON.parse()或类似的东西来解析它。

In short, if there is an easier way to get just the IDs and the values, that would be great.简而言之,如果有一种更简单的方法来获取 ID 和值,那就太好了。 If I have to create an array and then iterate over that to pull the Ids and values I can do that as well.如果我必须创建一个数组,然后对其进行迭代以提取 Id 和值,我也可以这样做。 I've tried a few things, and I'm banging my head against the wall because the structure of the form isn't consistent.我已经尝试了一些东西,但由于表单的结构不一致,我正将头撞到墙上。

Any help is greatly appreciated.任何帮助是极大的赞赏。

I hope this will help you.我希望这能帮到您。

 const labels = document.getElementsByTagName("label"); Array.from(labels).forEach(label => { const labelText = label.innerHTML; const labelId = label.getAttribute('id'); console.log(labelText); console.log(labelId); });
 <label id="label_id_1">Lable 1</label><br> <label id="label_id_2">Lable 2</label><br> <label id="label_id_3">Lable 3</label><br> <label id="label_id_4">Lable 4</label><br> <label id="label_id_5">Lable 5</label><br>

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

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