简体   繁体   English

Div可编辑并绑定到输入

[英]Div contenteditable and binding to an input

v-ajax is a directive I have that automatically submits the form when you press submit. v-ajax是我拥有的指令,当您按Submit时,它会自动提交表单。 The form grabs all my input, serializes them and submits them via ajax. 该表单将获取我的所有输入,将其序列化并通过ajax提交。 Now for one of my forms, instead of using a TextArea I want to allow bolds and italics so I'm using a div with the contenteditable attribute. 现在,对于我的一种表单,我不想使用TextArea而是允许使用粗体和斜体,因此我使用的是具有contenteditable属性的div

Here's a stripped down version of what I'm trying to accomplish. 这是我要完成的工作的简化版本。

<form v-ajax action="someurl">
    <div contenteditable>{{ message }}</div>
    <input name="content" type="hidden" value="{{ message}}">
    ... bunch  of other inputs...
    <input type="submit" value="Save">
</form>

My question is, how can I make it so that whatever the person types in the div automatically populates the value of the input with the name of content. 我的问题是,我该如何做到这一点,以便无论div中的任何人输入,都会自动使用内容名称填充输入的值。

Here's one way to populate the hidden input with whatever's typed into the div: 这是一种使用div中键入的内容填充隐藏输入的方法:

First, so you can access them, give the div and hidden input unique IDs: 首先,您可以访问它们,为div和隐藏的输入提供唯一的ID:

<div id="contenteditable" contenteditable>...</div>
...
<input id="content" name="content" type="hidden" value="{{ message}}">

Then use JavaScript to listen for keyup events on the div, and set the input's value to the text in the div: 然后使用JavaScript监听div上的keyup事件,并将输入的值设置为div中的文本:

var editDiv = document.getElementById('contenteditable');
editDiv.addEventListener( 'keyup', function () {
    var hiddenInput = document.getElementById('content');
    hiddenInput.value = this.textContent;
});

Here's a jsfiddle . 这是一个jsfiddle

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

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