使用 JavaScript 插入元素时无法接收表单输入数据

Posted

技术标签:

【中文标题】使用 JavaScript 插入元素时无法接收表单输入数据【英文标题】:form inputs data failed to be received when element is inserted with JavaScript 【发布时间】:2021-07-24 18:47:07 【问题描述】:

我正在尝试根据用户想要上传的内容动态更改父表单元素的 html 以显示,然后从该子元素中检索数据。我保存了子列表以在 js 文件夹中动态输入,使父表单元素为空。 问题是:

a) 当我根据用户要上传的内容动态输入首选子元素时,即使它在 DOM 中显示该元素存在,它也不会检索值。

b) 而如果我在 html 文件夹中静态输入子元素,它就可以正常工作。但是当孩子再次改变时,它仍然是我得到的静态输入值。 请问我该怎么做?这是显示它的代码笔。

 <div class="upload-box container mt-3">
    <div class="title-box-d">
      <h3 class="title-d upload-type">Uploading A Car</h3>
    </div>
    <div class="box-collapse-wrap form ">
      <div class="form-group mb-5">
        <div class="row">
          <div class="col-md-4">
            <label for="upload">What Do You Want To Upload?</label>
            <select class="form-control form-control-lg form-control-a" id="upload">
              <option value="cars">Car</option>
              <option value="houses">House/Home</option>
              <option value="land">Land Properties</option>
            </select>
          </div>
        </div>
      </div>

      <form class="form-a form-upload">
    </div>
    </form>
  </div>
  </div>

JS


  ///////////////////////
  /*--/ Project Logic /--*/
  //////////////////////

  const projectData = 
    uploadCategories: 
      carForm: ` <div class="row">
      <div class="col-md-8 mb-2">
        <div class="form-group">
          <label for="file">Add Photo</label>
          <input type="file" id="file" accept="image/*" multiple="multiple"
            class="form-control form-control-lg form-control-a">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="location">Location</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="location">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="brand">Car Brand</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="brand"
            placeholder="Eg Toyota, Lexus etc">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="car-model">Car Model</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="car-model"
            placeholder="eg Venza, Sienna, Corolla Etc">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="year">Year</label>
          <input type="number" class="form-control form-control-lg form-control-a" id="year">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="condition">Condition</label>
          <select class="form-control form-control-lg form-control-a" id="condition">
            <option>Brand New</option>
            <option>Nigerian Used</option>
            <option>Foreign Used</option>
          </select>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="transmission">Transmission</label>
          <select class="form-control form-control-lg form-control-a" id="transmission">
            <option>Automatic</option>
            <option>Manual</option>
          </select>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="registered">Registered?</label>
          <select class="form-control form-control-lg form-control-a" id="registered">
            <option>Yes</option>
            <option>No</option>
          </select>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="mileage">Mileage</label>
          <input type="number" class="form-control form-control-lg form-control-a" id="mileage"
            placeholder="Mileage (km)">

          <div class="form-group mt-3">
            <label for="price">Price</label>
            <input type="number" class="form-control form-control-lg form-control-a" id="price">
          </div>
        </div>
      </div>
      <div class="col-md-8 mb-2">
        <div class="form-group">
          <label for="description">Description</label>
          <textarea class="form-control form-control-lg form-control-a"
            placeholder="Add more description to your Ad" id="description" cols="30" rows="30"
            style="height: 10rem;"></textarea>
        </div>
      </div>
      <div class="col-md-12">
        <button type="submit" class="btn btn-b">Upload</button>
      </div>
    </div>`,
      houseForm: `<div class="row">
      <div class="col-md-8 mb-2">
        <div class="form-group">
          <label for="file">Add Photo</label>
          <input type="file" id="file" accept="image/*" multiple="multiple"
            class="form-control form-control-lg form-control-a">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="location">Location</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="location">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="title">Title</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="title"
            placeholder="Title or name of the Property">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="area">Property Size (sqm)</label>
          <input type="number" class="form-control form-control-lg form-control-a" id="area">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="bedrooms">Bedrooms</label>
          <input type="number" class="form-control form-control-lg form-control-a" id="bedrooms">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="bathrooms">Bathrooms</label>
          <input type="number" class="form-control form-control-lg form-control-a" id="bathrooms">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="sale-status">For Sale Or rent?</label>
          <select class="form-control form-control-lg form-control-a" id="sale-status">
            <option>For Sale</option>
            <option>For Rent</option>
          </select>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="row">

          <div class="col-6">
            <div class="form-group">
              <label for="garage">Garage</label>
              <input type="number" class="form-control form-control-lg form-control-a" id="garage">
            </div>
          </div>

          <div class="col-6">
            <div class="form-group">
              <label for="price">Price</label>
              <input type="number" class="form-control form-control-lg form-control-a" id="price">
            </div>
          </div>
        </div>

      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="amenities">Other Amenities</label>
          <select class="form-control form-control-lg form-control-a" id="amenities" multiple style="height: 10rem;">
            <option>Parking Space</option>
            <option>24 Hours Electricity</option>
            <option>Internet</option>
            <option>Air Conditioning</option>
            <option>Security</option>
            <option>Balcony</option>
            <option>Tile Floor</option>
            <option>Dish Washer</option>
            <option>Dining Area</option>
            <option>Kitchen Cabinet</option>
            <option>Kitchen Shelf</option>
            <option>Wardrobe</option>
            <option>WIFI</option>
            <option>POP Ceiling</option>
            <option>Prepaid Meter</option>
            <option>Concrete Flooring</option>
          </select>
        </div>
      </div>
      <div class="col-md-8 mb-2">
        <div class="form-group">
          <label for="description">Description</label>
          <textarea class="form-control form-control-lg form-control-a" placeholder="Add more description to your Ad"
            id="description" cols="30" rows="30" style="height: 10rem;"></textarea>
        </div>
      </div>
    </div>
    <div class="col-md-12">
      <button type="submit" class="btn btn-b">Upload</button>
                  </div>`,
      landForm: `<div class="row">
      <div class="col-md-8 mb-2">
        <div class="form-group">
          <label for="file">Add Photo</label>
          <input type="file" id="file" accept="image/*" multiple="multiple"
            class="form-control form-control-lg form-control-a">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="location">Location</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="location">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="title">Title</label>
          <input type="text" class="form-control form-control-lg form-control-a" id="title"
            placeholder="Title or name of the Land.">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="area">Property Size (sqm)</label>
          <input type="number" class="form-control form-control-lg form-control-a" id="area">
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="land-type">Type Of Land</label>
          <select class="form-control form-control-lg form-control-a" id="land-type" placeholder="What Type of Land is This?">
            <option>Commercial Land</option>
            <option>Farmland</option>
            <option>Industrial Land</option>
            <option>Mixed-use LAnd</option>
            <option>Quarry</option>
            <option>Residential Land</option>
          </select>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="row">
          <div class="col-12">
            <div class="form-group">
              <label for="sale-status">For Sale Or Lease?</label>
              <select class="form-control form-control-lg form-control-a" id="sale-status">
                <option>For Sale</option>
                <option>For Lease</option>
              </select>
            </div>
          </div>
          <div class="col-12">
            <div class="form-group">
              <label for="price">Price</label>
              <input type="number" class="form-control form-control-lg form-control-a" id="price">
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="amenities">Other Amenities</label>
          <select class="form-control form-control-lg form-control-a" id="amenities" multiple style="height: 10rem;">
            <option>Parking Space</option>
            <option>Electric Supply</option>
            <option>Domestic Sewage</option>
            <option>Gas Supply</option>
            <option>Rain Water Drainage</option>
            <option>Water Supply</option>
          </select>
        </div>
      </div>
      <div class="col-md-4 mb-2">
        <div class="form-group">
          <label for="description">Description</label>
          <textarea class="form-control form-control-lg form-control-a" placeholder="Add more description to your Ad"
            id="description" cols="30" rows="30" style="height: 10rem;"></textarea>
        </div>
      </div>
    </div>
    <div class="col-md-12">
      <button type="submit" class="btn btn-b">Upload</button>
                 </div>`
    ,

    fromInputs: 
      Name: $('#title'),
      Brand: $('#brand'),
      Model: $('#car-model'),
      Location: $('#location'),
      Description: $('#description'),
      Status: $('#sale-status'),
      Price: $('#price'),
      Bedrooms: $('#bedrooms'),
      Bathrooms: $('#bathrooms'),
      Garage: $('#garage'),
      Area: $('#area'),
      Amenities: $('#amenities'),
      'Type Of Land': $('#land-type'),
      Year: $('#year'),
      Condition: $('#condition'),
      Transmission: $('#transmission'),
      Registered: $('#registered'),
      Mileage: $('#mileage'),
    ,

    formImages: 
      dataReferenceId: 'dataid',
      images: []
    ,

    dataToSubmit : ''
  ;

  /*--/ Admin Page Code /--*/

  // Check what typemof data user wants to upload and display from related to that
  $('#upload').change(e => 

    switch (e.target.value) 
      case 'houses':
        $('.upload-type').text('Uploading A House');
        $('.form-upload').html(projectData.uploadCategories.houseForm);
        break;

      case 'land':
        $('.upload-type').text('Uploading A Land');
        $('.form-upload').html(projectData.uploadCategories.landForm);
        break;

      default:
        $('.upload-type').text('Uploading A Car');
        $('.form-upload').html(projectData.uploadCategories.carForm);
        break;
    
  );


  // GET ALL UPLOAD FORM DATA INPUTED
  $('.form-upload').submit(function (event) 
    event.preventDefault();

    // Check what category user wants to upload
    const uploadCategory = $('#upload').val();

    // GET ALL THE DATA FOR A FORM SESSION UPLOADED
    const data = Object.entries(projectData.fromInputs).map(([key, value]) => [key, value && value.val()]);

    // FILTER THE DATA TO RETURN ON THOSE WITH VALUES 
     const filteredData = Object.fromEntries(
      data.filter(([key, value]) => value
    ));

    console.log(filteredData);
    // projectData.dataToSubmit = filteredData;

  );

编解码器:https://codepen.io/genral-walker/pen/vYgqbvL

【问题讨论】:

请创建minimal reproducible example。编写尽可能小的版本,确保它正常工作,然后扩展它。 【参考方案1】:

主要问题是您正在缓存对当时可能不在 DOM 中的元素的引用。你应该存储一个选择器:

fromInputs: 
  Name: '#title',
  Brand: '#brand',
  Model: '#car-model',
  Location: '#location',
  Description: '#description',
  Status: '#sale-status',
  Price: '#price',
  Bedrooms: '#bedrooms',
  Bathrooms: '#bathrooms',
  Garage: '#garage',
  Area: '#area',
  Amenities: '#amenities',
  'Type Of Land': '#land-type',
  Year: '#year',
  Condition: '#condition',
  Transmission: '#transmission',
  Registered: '#registered',
  Mileage: '#mileage',
,

稍后再查找:

const data = Object.entries(projectData.fromInputs).map(([key, value]) => 
  console.log(key, value);
  const $el = $(value);
  return [key, $el.length && $el.val()];
);

https://codepen.io/genral-walker/pen/vYgqbvL?editors=1111

【讨论】:

非常感谢,我完全没想到!

以上是关于使用 JavaScript 插入元素时无法接收表单输入数据的主要内容,如果未能解决你的问题,请参考以下文章

我无法将表单信息插入我的数据库中,我不断收到 404 错误

无法在 Firefox 上从 Javascript 提交表单

显示时将相同的 HTML 表单元素插入到多个模式中,但验证不起作用

无法使用 jQuery 定位动态生成的元素

如何重复 JavaScript 表单验证,直到所有输入都正确,然后将输入插入数据库?

表单标签中的按钮不会提交或响应Javascript / Jquery