繁体   English   中英

如何在表单中发布 Quill 编辑器的内容?

[英]How do I post contents of a Quill editor in a form?

我有一个我认为很常见的情况。 我通常会有这种形式:

<form method="post">

<textarea name="text"></textarea>
<input type="submit" value="Save" />

</form>

然后使用 PHP 我将从表单 ($_POST['text']) 中捕获数据,然后我可以在另一个变量中使用它。

现在,我想使用Quill ,这样用户就有了一个不错的富文本编辑器。 Quill 似乎非常适合这一点,并且文档非常详细。 但是,由于某种原因,我找不到如何将数据“发布”到表单。 有一个示例页面可以满足我的要求,但我无法在我的示例中完全实现这一点,并且在快速入门指南中没有讨论这个相当基本的(对我而言)主题,我找不到这个在文档中。

Quill应该这样使用吗? 我在监督什么吗? 有推荐的方法来完成这项工作吗?

这是我目前拥有的:

<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">
</head>
<body>
<form method="post">


<!-- Create the toolbar container -->
<div id="toolbar">
  <button class="ql-bold">Bold</button>
  <button class="ql-italic">Italic</button>
</div>


<form method="post">

<!-- Create the editor container -->
<div id="editor">
  <p>Hello World!</p>
</div>

<input type="submit" value="Save" />

</form>

<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
  var editor = new Quill('#editor', {
    modules: { toolbar: '#toolbar' },
    theme: 'snow'
  });
</script>
</body>
</html>
<form method="post" id="identifier">

<div id="quillArea"></div>

<textarea name="text" style="display:none" id="hiddenArea"></textarea>
<input type="submit" value="Save" />

</form>

如果您给表单一个标识符,那么使用 jQuery 您可以执行以下操作:

var quill = new Quill ({...}) //definition of the quill

$("#identifier").on("submit",function(){
$("#hiddenArea").val($("#quillArea").html());
})

您可以使用 quill.getContents() 来获取增量,而不是 HTML。

你可以查看相关讨论https://github.com/quilljs/quill/issues/87

虽然这不是一个理想的解决方案:

var myEditor = document.querySelector('#editor')
var html = myEditor.children[0].innerHTML

这是我用来执行此操作的代码:

 $(document).ready(function(){ $("#theform").on("submit", function () { var hvalue = $('.ql-editor').html(); $(this).append("<textarea name='content' style='display:none'>"+hvalue+"</textarea>"); }); });

基本上,它所做的是向表单添加一个隐藏的文本区域,并将“ql-editor”容器(这是由容器 div 中的 Quill Editor 自动制作)的内容复制到其中。 然后 textarea 将与表单一起提交。 您需要将代码中使用的 ID 更改为容器标签的 ID。

我想出的一个解决方案是制作一个包装类。

class QuillWrapper {

    /**
     * @param targetDivId { string } The id of the div the editor will be in.
     * @param targetInputId { string } The id of the hidden input
     * @param quillOptions { any } The options for quill
     */
    constructor(targetDivId, targetInputId, quillOptions) {

        //Validate target div existence
        this.targetDiv = document.getElementById(targetDivId);
        if (!this.targetDiv) throw "Target div id was invalid";

        //Validate target input existence
        this.targetInput = document.getElementById(targetInputId);
        if (!this.targetInput) throw "Target input id was invalid";

        //Init Quill
        this.quill = new Quill("#" + targetDivId, quillOptions);

        //Bind the two containers together by listening to the on-change event
        this.quill.on('text-change',
            () => {
                this.targetInput.value = this.targetDiv.children[0].innerHTML;
            });
    }
}

只需将类包含在页面上的某处,然后使用以下内容来初始化它:

    let scopeEditor = new QuillWrapper("ScopeEditor", "Scope", { theme: "snow" });

您的 html 大致如下所示:

<div class="form-group">
     <label asp-for="Scope" class="control-label col-md-2"></label>  
     <div id="ScopeEditor"></div>
     <input type="hidden" asp-for="Scope" class="form-control" />
</div>

我这样做:

var quill = new Quill('.quill-textarea', {
            placeholder: 'Enter Detail',
            theme: 'snow',
            modules: {
                toolbar: [
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'indent': '-1'}, { 'indent': '+1' }]
                ]
            }
        });

        quill.on('text-change', function(delta, oldDelta, source) {
            console.log(quill.container.firstChild.innerHTML)
            $('#detail').val(quill.container.firstChild.innerHTML);
        });

表格上的某处:

<div class="quill-textarea"></div>
<textarea style="display: none" id="detail" name="detail"></textarea>

我知道这个问题已经解决了,但我想补充一点信息。 要获取 Quill 中存在的数据,您不需要 jQuery 或其他技巧。 我建议看看这个答案:

https://stackoverflow.com/a/42541886/2910546

我还应该在这里做个笔记:作者的问题至少在 2 年前就被问到了。 所以,今天,我相信这是解决这个问题的最可行的方法。

有关 Quill 的更多信息、案例研究示例以及常见问题和答案,请访问以下链接:

https://github.com/loagit/Quill-Examples-and-FAQ

在这里解决

如何将 Quill.js 值保存到 Laravel 5.6 数据库

添加隐藏输入:

<input type="hidden" name="body"/>

JS代码:

var form = document.getElementById("FormId"); // get form by ID

form.onsubmit = function() { // onsubmit do this first
                             var name = document.querySelector('input[name=body]'); // set name input var
                             name.value = JSON.stringify(quill.getContents()); // populate name input with quill data
                             return true; // submit form
                           }
To set contents to quill do this :

quill.setContents({!! $post->body !!});

这就是我使用的,您所要做的就是为您的编辑器标签提供data-name属性。 这将创建一个隐藏输入作为编辑器标签的同级并将 html 内容放入其中。 您可以获得其他格式的内容,如果您需要知道如何获取它们,我会留下未使用的变量。

html:

<div class="field editor" data-name="experience"></div>

js:

let quill_element = document.querySelector('.editor')
let quill = new Quill(quill_element, {
    modules: {
        toolbar: '#toolbar'
    },
    placeholder: document.querySelector('.editor').getAttribute('data-placeholder'),
    theme: 'bubble',
});

let hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = quill_element.getAttribute('data-name');
quill_element.parentElement.appendChild(hiddenInput);

quill.on('text-change', function () {
    let justHtml = quill.root.innerHTML;
    hiddenInput.value = justHtml;
    // other formats if you like to use..
    var delta = editor.getContents();
    var text = editor.getText();
});

尝试这个:

<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
    var quill = new Quill('#editor', {
        modules: {
            toolbar: [
                ['bold', 'italic'],
                ['link', 'blockquote', 'code-block', 'image'],
                [{
                    list: 'ordered'
                }, {
                    list: 'bullet'
                }]
            ]
        },
        placeholder: 'Compose an epic...',
        theme: 'snow'
    });

    $("#form").submit(function() {
        $("#description").val(quill.getContents());
    });
</script>

这对我有用:

<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
    var quill = new Quill('#editor', {
        modules: {
            toolbar: [
                ['bold', 'italic'],
                ['link', 'blockquote', 'code-block', 'image'],
                [{
                    list: 'ordered'
                }, {
                    list: 'bullet'
                }]
            ]
        },
        placeholder: 'Compose an epic...',
        theme: 'snow'
    });

    $("#form").submit(function() {
        $("#description").val(quill.getContents());
    });
</script>

这个解决方案对我来说很好用:

    <script type="text/javascript">
    $(document).ready(function(){
      $("#emailForm").on("submit", function () {
        var hvalue = $('.editor').text();
        $(this).append("<textarea name='message' style='display:none'>"+hvalue+"</textarea>");
       });
    });
    </script>

我如下解决了这个问题。

在将成为编辑器容器的元素中,我设置了一个 like 属性,data-input-name="something"

在实例化编辑器后,我只是编写了一个简单的代码,将 quill 的内部值分配给隐藏输入

quill.on('text-change', function() {
              let content = quill.root.innerHTML.trim();
              let targetId = quill.container.dataset.inputName
              document.querySelector(`#${targetId}`).setAttribute("value", content);
          });

签出这个 repo,它可能会有所帮助。 它很容易安装。

https://github.com/tangien/quilljs-textarea

AutoInitialize Quilljs 只需将属性data-quilljs添加到 textarea 元素和 rest 插件将处理它。

而已!

我发现页面上的prevoius解决方案在复制到隐藏字段时也在字段末尾复制了很多quiill标记html。

此页面上描述的解决方案似乎纠正了这一点:

https://lucidar.me/en/rich-content-editor/how-to-get-html-content-from-quill-rich-editor/

基本上,使用以下命令访问纯 HTML:

var html = quil.root.innerHTML
document.getElementById("descriptionHidden").value = html;

链接 CSS:

<!-- CSS Implementing Plugins -->
<link rel="stylesheet" href="https://htmlstream.com/preview/front-v4.2/html/assets/css/vendor.min.css">
<link rel="stylesheet" href="https://htmlstream.com/preview/front-v4.2/html/assets/vendor/bootstrap-icons/font/bootstrap-icons.css">
<!-- CSS Front Template -->
<link rel="stylesheet" href="https://htmlstream.com/preview/front-v4.2/html/assets/css/theme.min.css?v=1.0">

链接 JS:

<!-- JS Implementing Plugins -->
<script src="https://htmlstream.com/preview/front-v4.2/html/assets/js/vendor.min.js"></script>
<!-- JS Front -->
<script src="https://htmlstream.com/preview/front-v4.2/html/assets/js/theme.min.js"></script>

恩米 html:

<form id="form-perfil" name="form-perfil" method="POST">
  <!-- Form Group -->
  <div class="row form-group">
    <label class="col-sm-3 col-form-label input-label">BIO</label>

    <div class="col-sm-9">
      <!-- Quill -->
      <div class="quill-custom">
        <div
          class="js-quill"
          style="min-height: 15rem;"
          data-hs-quill-options='{
                       "placeholder": "Type your message...",
                        "modules": {
                          "toolbar": [
                            ["bold", "italic", "underline", "strike", "link", "image", "blockquote", "code", {"list": "bullet"}]
                          ]
                        }
                       }'
        >
          Creative mind at Htmlstream
        </div>
      </div>
      <!-- End Quill -->
      <textarea name="text_quill" style="display: none;" id="text_quill"></textarea>
    </div>
  </div>
  <!-- End Form Group -->

  <button type="submit" class="mt-3 float-right btn btn-primary">Enviar formulario</button>
  <!-- End Form Group -->
</form>

恩米 JS:

// INITIALIZATION OF QUILLJS EDITOR
// =======================================================
var quill = $.HSCore.components.HSQuill.init('.js-quill');

// =======================================================
$("#form-perfil").on("submit", function (e) { 
  e.preventDefault(); //No se activará la acción predeterminada del evento

  $("#text_quill").val($(".ql-editor").html());

  var formData = new FormData($("#form-perfil")[0]);
  $.ajax({
    url: "ajax/pago_administrador.php",
    type: "POST",
    data: formData,
    contentType: false,
    processData: false,
    success: function (datos) {  },             
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM