Search code examples
javascriptformssubmit

Submit div content as textarea with hidden fields


Got a form and I need to submit the content of five divs. I read many solutions and I figured I could use hidden fields, but I don't know how. Javascript or jquery would be great

<form name="module" id="module" method="post" action=""  title="postthis">

<div name="mytext"  id="mytext">Here's something I want to pass</div>
<div name="mytext2"  id="mytext2">Again, I want this div to act as a text area</div>
<div name="mytext3"  id="mytext3">Another text</div>
<div name="mytext4"  id="mytext4">Yet another</div>
<div name="mytext5"  id="mytext5">Last one</div>

<input name="mytext" type="hidden" id="mytext" value="mytext" />
<input name="mytext2" type="hidden" id="mytext2" value="mytext3" />
<input name="mytext3" type="hidden" id="mytext3" value="mytext4" />
<input name="mytext4" type="hidden" id="mytext4" value="mytext5" />
<input name="mytext5" type="hidden" id="mytext5" value="mytext6" />

<input name="insert" type="submit" class="btn btn-primary" id="insert" value="Save my fields" onClick="return validate_login(module);" />
</form>

Solution

  • Please see below code snippet. to help you achieve your goals. This solution is broken into two parts, the HTML markup and the Javascript code. data-input is used to connect corresponding hidden fields ids. These is then submitted to the server for processing.

    function augmentValues(divClass = "mytext") {
      const divs = document.getElementsByClassName(divClass);
      Array.from(divs).forEach(divElem => {
        const inputId = divElem.getAttribute("data-input");
        const hiddenInput = document.getElementById(`${inputId}`)
        hiddenInput.value = divElem.textContent
      })
      
    }
    
    
    function handleSubmit(event) {
      event.preventDefault()
      augmentValues();
      const formData = new FormData(event.target);
      const formValues = Object.fromEntries(formData.entries())
      // Validate inputs
      // Submit form
      console.log(formValues)
      event.target.submit()
    }
    <form name="module" id="module" method="post" action="" title="postthis" onsubmit="handleSubmit(event)">
    
      <div class="mytext" data-input="mytext">Here's something I want to pass</div>
      <div class="mytext" data-input="mytext2">Again, I want this div to act as a text area</div>
    
      <input name="mytext" type="hidden" id="mytext" value="" />
      <input name="mytext2" type="hidden" id="mytext2" value="" />
    
      <button name="insert" type="submit" class="btn btn-primary">
    Save my fields
    </button>
    </form>