46

So I have a bunch of paragraph elements which are dynamically populated from a db. I have made the elements contenteditable. I now want to submit edits back the the db via a standard form submission. Is there a way to post the contenteditable elements back?

Jason Sundram
  • 11,598
  • 19
  • 69
  • 86
MFB
  • 17,535
  • 25
  • 70
  • 115

3 Answers3

40

You have to use javascript one way or the other, it won't work as a "standard" form element as it would with a textarea or the like. If you like, you could make a hidden textarea within your form, and in the form's onsubmit function copy the innerHTML of the contenteditable to the textarea's value. Alternatively you could use ajax/xmlHttpRqeuest to submit the stuff a bit more manually.

function copyContent () {
    document.getElementById("hiddenTextarea").value =  
        document.getElementById("myContentEditable").innerHTML;
    return true;
}


<form action='whatever' onsubmit='return copyContent()'>...
Jason Sundram
  • 11,598
  • 19
  • 69
  • 86
rob
  • 9,687
  • 6
  • 41
  • 71
  • 2
    It seems it is better to use `innerText`, or you'll get put all invisible markup into textarea. – denis.peplin Mar 10 '17 at 19:24
  • 2
    That's the point. You need all that markup, why else would you use a contentEditable? Remember the textarea is hidden, it is just used to hold the contents prior to sending it to the server. – rob Mar 10 '17 at 23:00
2

If anyone is interested I patched up a solution with VueJS for a similar problem. In my case I have:

<h2 @focusout="updateMainMessage" v-html="mainMessage" contenteditable="true"></h2>
<textarea class="d-none" name="gift[main_message]" :value="mainMessage"></textarea>

In "data" you can set a default value for mainMessage, and in methods I have:

methods: {
  updateMainMessage: function(e) {
    this.mainMessage = e.target.innerText;
  }
}

"d-none" is a Boostrap 4 class for display none. Simple as that, and then you can get the value of the contenteditable field inside "gift[main_message]" during a normal form submit for example, no AJAX required. I'm not interested in formatting, therefore "innerText" works better than "innerHTML" for me.

Alberto T.
  • 438
  • 3
  • 7
0

Does it NEED to be standard form submission? If you cannot or do not want use a form with inputs, you may try AJAX (XMLHttpRequest + FormData), through which you could perform asynchronous requests and control better how response shows up.

If you want it even simpler, try jQuery's $.ajax function (also $.get and $.post). It sends data using simple JS objects.

Johannes Müller
  • 5,280
  • 1
  • 11
  • 24
  • An example of XHR working with FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects –  Oct 10 '17 at 20:19