简体   繁体   中英

Div contenteditable and binding to an input

v-ajax is a directive I have that automatically submits the form when you press submit. The form grabs all my input, serializes them and submits them via 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.

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.

Here's one way to populate the hidden input with whatever's typed into the div:

First, so you can access them, give the div and hidden input unique IDs:

<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:

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

Here's a jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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