【问题标题】:How to alter the attributes of a form's fields without clearing the field values?如何在不清除字段值的情况下更改表单字段的属性?
【发布时间】:2021-06-20 16:45:24
【问题描述】:

所以我有这个 html 表单:

<form action="">
        <input type="text" name="form-0-product_name" id="id-form-0-product_name">
        <input type="text" name="form-0-product_price" id="id-form-0-product_price">
        <button>Change form</button>
</form>

请注意 name 和 id 属性以及它们如何包含“form-0”。出于一个无关紧要的原因,我希望用户能够单击“更改表单”按钮并将“form-0”的所有实例更改为“form-1”。我想出了这个 javascript 函数:

let button = document.querySelector("button");
let form = document.querySelector("form");

button.addEventListener("click", e => {
    e.preventDefault();
    const replacedForm = "form-0";
    form.innerHTML = form.innerHTML.replaceAll(replacedForm, "form-1");
})

这可以将“form-0”字符串替换为“form-1”;但是,这似乎完全重置了表单。换句话说,如果客户端已经在文本字段中输入了一些数据,然后按下更改表单按钮,则这些字段的值将被清除。我想知道的是,是否有一种真正有效的方法可以更改表单字段的属性(主要是 id 和 name),而无需清除字段的值(如果它们是其中的值)。谢谢,如果我需要澄清,请告诉我。

【问题讨论】:

  • 为什么要更换html来改变id/name?
  • 我不知道,但这就是我提出问题的原因。我正在寻求一种更好的方法来做到这一点。我不只是想改变id,我也在尝试改变名字

标签: javascript html forms dom


【解决方案1】:

您必须逐个迭代元素和属性。

let button = document.querySelector("button");
let form = document.querySelector("form");

button.addEventListener("click", e => {
  e.preventDefault();
  const replacedForm = "form-0";
  // Select all elements with a name or id
  for (const elm of form.querySelectorAll('[name], [id]')) {
    for (const attrib of ['name', 'id']) {
      elm[attrib] = elm[attrib].replaceAll(replacedForm, "form-1");
    }
  }
})
<form action="">
  <input type="text" name="form-0-product_name" id="id-form-0-product_name">
  <input type="text" name="form-0-product_price" id="id-form-0-product_price">
  <button>Change form</button>
</form>

但在大多数情况下,这真的很奇怪。 ID 尤其不应该是动态的。强烈考虑是否有其他方法可以解决您要解决的问题。

【讨论】:

  • 哇哦。我很尴尬地承认这一点,但我已经用 JavaScript 编程一年了,我不知道你可以在单个元素上调用 querySelectorAll()。这解决了我的问题。谢谢!
【解决方案2】:

你也可以遍历form.elements,修改属性的value属性

const form = document.querySelector('form');

Array.from(form.elements).forEach(el => {
  Array.from(el.attributes).forEach(att => {
    att.value = att.value.replaceAll('form-0', 'form-1')
    console.log(att.value)
  });
})
<form action="">
        <input type="text" name="form-0-product_name" id="id-form-0-product_name">
        <input type="text" name="form-0-product_price" id="id-form-0-product_price">
        <button>Change form</button>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多