Using HTML5, how do I use contenteditable fields i

2019-01-05 03:06发布

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?

4条回答
混吃等死
2楼-- · 2019-01-05 03:22

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.

查看更多
祖国的老花朵
3楼-- · 2019-01-05 03:29

If you use jquery, you could submit the content with a .click() event (i.e "save" or "submit"...)

In your click function post it to a server side script using an ajax "post" to insert it into your database.

Example

查看更多
唯我独甜
4楼-- · 2019-01-05 03:37

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()'>...
查看更多
放荡不羁爱自由
5楼-- · 2019-01-05 03:42

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.

查看更多
登录 后发表回答