0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

innerHTMLを取り出したらinputのvalueが反映されていない

Posted at

こいつのせいで1時間かかる作業を手動でやり直す羽目になりました。

問題

ここに次のような html があります。

.html
<div id="wrap">
  <input type="text" value="default"><br>
  <input type="checkbox"><br>
  <input type="button" value="submit">
</div>
<script>
  function subm(){
    console.log(wrap.innerHTML)
  };
</script>

image.png

フォームを入力して…

image.png

送信!……あれ?

console
<input type="text" value="default"><br> <input type="checkbox"><br> <input type="button" onclick="subm()" value="submit">

value が全く反映されていません。

解決策

JavaScript で input を forEach して、解決するしかありません。

.html
<div id="wrap">
  <input type="text" value="default"><br>
  <input type="checkbox"><br>
  <input type="button" value="submit">
</div>
<script>
  function subm(){
    console.log(getInnerHTMLWithValues(wrap))
  };

  function getInnerHTMLWithValues(targetElement) {
    const clone = targetElement.cloneNode(true);

    const originalInputs = targetElement.querySelectorAll('input, textarea, select');
    const clonedInputs = clone.querySelectorAll('input, textarea, select');

    for (let i = 0; i < originalInputs.length; i++) {
      const original = originalInputs[i];
      const cloned = clonedInputs[i];

      if (original.tagName === 'INPUT') {
        const type = original.type;
        if (type === 'checkbox' || type === 'radio') {
          if (original.checked) {
            cloned.setAttribute('checked', 'checked');
          } else {
            cloned.removeAttribute('checked');
          };
        } else {
          cloned.setAttribute('value', original.value);
        };
      }
    
      else if (original.tagName === 'TEXTAREA') {
        cloned.textContent = original.value;
        cloned.innerHTML = original.value;
      }

      else if (original.tagName === 'SELECT') {
        const options = cloned.querySelectorAll('option');
        for (let j = 0; j < options.length; j++) {
          if (j === original.selectedIndex) {
            options[j].setAttribute('selected', 'selected');
          } else {
            options[j].removeAttribute('selected');
          };
        };
        cloned.setAttribute('value', original.value);
      };
    };
    return clone.innerHTML;
  };

</script>

今度こそ…

image.png

console
<input type="text" value="value"><br> <input type="checkbox" checked="checked"><br> <input type="button" onclick="subm()" value="submit">

しっかり反映されました!

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?