Passing a contenteditable element through form?

Steve Gates

I've been working weeks at trying to figure out a way to pass a contenteditable element through a form on 'submit'.

  • Yes I know I can pass data through input/textarea but I can't due to design reasons (and no it can't be solved with simple css)

Now I'm trying to assign the value of the contenteditable elements to the value of the hidden inputs so that when submit button is clicked it will pass along the data copied from the contenteditable into the input.

The problem is that when typing in the contenteditable element, the hidden input fields are not auto-updating live.

JS

    jQuery(function($) {
            var input = $('#title'),
                preview = $('form-title');

            var input = $('#message'),
                preview = $('form-message');

            input.keyup(function(e) {
                preview.text(input.val());
            });
        });​
/* I tried this and it didn't work:  function getContent(){
        document.getElementById("title").value = document.getElementById("form-title").innerHTML;
    } */

HTML

<h1 contenteditable="true" id="title">Type your title here</h1>
<p contenteditable="true" id="message">messages</p>

<form id="form" method="post">
    <input type="text" name="title" id="form-title" style="display:none;"></input>
    <textarea name="message" id="form-message" style="display:none;"></textarea>
    <input type="submit" id="theSubmit" style="display:none;" value="submit"></input>
</form>

Any suggestions? Please test your answers before posting :) Thank you!

Sam

No need to live update (and you shouldn't, for performance reasons) your input fields. Use a submit listener on the form and update the input values:

var $form = $('form');
$form.submit(function(e) {
    var title = $('#title').text(),
        message = $('#message').text();

    $form.find('input[name="title"]').val(title);
    $form.find('textarea[name="message"]').val(message);
});

JSFiddle

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related