简体   繁体   中英

Extract fields ids and text from a form using javascript

I want to make a simple app with JS that identies the form fields which includes the id of the field and its corresponding Text.

For example, for the following site: https://freeditorial.com/en/register

在此处输入图像描述 I want for each textbox the id, and the text. For the first one this will be:

text: Email
id: "user_email"

I can do it with the following code:

form = document.getElementsByClassName("control-group")
form[0].innerText
form[0].querySelector("input").id

The problem is that this depends on the class name, which can change for each site. Is there a way to get this same data from the form?

I'm trying with:

var site_forms =  document.forms

If I check the text of the form the data seems to be all there:

site_forms[0].innerText

this is a segment of it:

<input id="user_role_ids" name="user[role_ids]" type="hidden" value="2">
<div class="control-group">
  <label for="user_email">Email</label>
  <div class="controls">
    <input type="text" value="" name="user[email]" id="user_email">
  </div>
</div>
<span id="erroremail" class="rightCol error"></span>
<div class="control-group">
  <label for="user_name">Name</label>
  <div class="controls">
    <input id="user_name" name="user[name]" size="30" type="text">
  </div>
</div>
<div class="control-group">
  <label for="user_last_name">Last Name</label>
  <div class="controls">
    <input id="user_last_name" name="user[last_name]" size="30" type="text">
  </div>
</div>
<div class="control-group">
  <label for="user_username">Name by which you publish</label>
  <div class="controls">
    <input type="text" value="" name="user[username]" id="user_username">
  </div>
</div>
<div class="control-group">
  <label for="user_country_code">Country</label>
  <div class="controls">
  <select id="user_country_id" name="user[country_id]">
    <option value="">Country</option>
    <option value="3">Afghanistan</option>
    <option value="6">Albania</option>

But I don't find a reliable way of extracting it.

From your code snippet all forms could be retrieved via

document.forms

Then concrete form could selected, eg first form document.forms[0] .

The next step is to retrieve form inputs and get their names or values :

document.forms[0].querySelectorAll('input')[0].value
document.forms[0].querySelectorAll('input')[0].name

// or iterate over form inputs
[...document.forms[0].querySelectorAll('input')].forEach(input => {
  console.log(input.name);
  console.log(input.value);
});

You may benefit from FormData() API .

With that you simply need to build up formData object with FormData() constructor:

const myForm = document.getElementById('myForm'),
      formData = new FormData(myForm)

Extract all of its entries either into array of key ( name attributes of <input> nodes) value pairs:

const formEntries = [...formData.entries()]

Or object:

const formEntries = Object.fromEntries(formData.entries())

Or you may get individual values, using get() method and pass the necessary key as an argument.

Following is a quick demo of that approach:

 const form = document.getElementById('myForm') form.addEventListener('submit', e => { e.preventDefault() const formData = new FormData(form), formEntries = Object.fromEntries(formData.entries()) console.log(formEntries) })
 <form id="myForm"><input id="user_role_ids" name="user[role_ids]" type="hidden" value="2"><div class="control-group"><label for="user_email">Email</label><div class="controls"><input type="text" value="" name="user[email]" id="user_email"></div></div><span id="erroremail" class="rightCol error"></span><div class="control-group"><label for="user_name">Name</label><div class="controls"><input id="user_name" name="user[name]" size="30" type="text"></div></div><div class="control-group"><label for="user_last_name">Last Name</label><div class="controls"><input id="user_last_name" name="user[last_name]" size="30" type="text"></div></div><div class="control-group"><label for="user_username">Name by which you publish</label><div class="controls"><input type="text" value="" name="user[username]" id="user_username"></div></div><div class="control-group"><label for="user_country_code">Country</label><div class="controls"><select id="user_country_id" name="user[country_id]"><option value="">Country</option><option value="3">Afghanistan</option><option value="6">Albania</option><input type="submit" /></form>

If, for whatever reason, you need more low level access to the child inputs of a form (corresponding DOM-nodes and their attributes), you may go for HTMLFormElement.elements property which returns HTMLCollection of all the child nodes, so you may traverse that (eg with Array.prototype.reduce() method) to build up an object of key value pairs:

const formData = [...form.elements].reduce((r,{name,value}) => 
   (value && (r[name]=value),r),{})

You may check out the demo for that, just as well:

 const form = document.getElementById('myForm') form.addEventListener('submit', e => { e.preventDefault() const formData = [...form.elements].reduce((r,{name,value}) => (value && (r[name]=value),r),{}) console.log(formData) })
 <form id="myForm"><input id="user_role_ids" name="user[role_ids]" type="hidden" value="2"><div class="control-group"><label for="user_email">Email</label><div class="controls"><input type="text" value="" name="user[email]" id="user_email"></div></div><span id="erroremail" class="rightCol error"></span><div class="control-group"><label for="user_name">Name</label><div class="controls"><input id="user_name" name="user[name]" size="30" type="text"></div></div><div class="control-group"><label for="user_last_name">Last Name</label><div class="controls"><input id="user_last_name" name="user[last_name]" size="30" type="text"></div></div><div class="control-group"><label for="user_username">Name by which you publish</label><div class="controls"><input type="text" value="" name="user[username]" id="user_username"></div></div><div class="control-group"><label for="user_country_code">Country</label><div class="controls"><select id="user_country_id" name="user[country_id]"><option value="">Country</option><option value="3">Afghanistan</option><option value="6">Albania</option><input type="submit" /></form>

Why don't you try grabbing direct id of the input and target its value?

const a = document.getElementById("user_email")

then a.id and a.innerValue works fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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