submit text from "div contenteditable"

John Johansen picture John Johansen · Feb 20, 2013 · Viewed 9.3k times · Source

I'm trying to find a working solution, but there is nothing useful at the moment. I have the following form:

<form id="searchform" action="/search" onsubmit="putText()">
<div class="section" >
<div class="edit"><div ContentEditable = "true" id="text"></div></div>
<div class="control" onclick="sbmt()"></div>
</div>
<input id="s" name="q" class="submit" type="submit" value="Send">
</form> 

with the following js:

$(window).load(function(){
$(document).ready(function() {
 $('.edit').keydown(function(e) {
     if(e.which == 13) {
         //debugger;
        $(this).blur().next().focus();
        return false;
      }
 });
 })
});


function ElementInit() {
  new SectionalElement({
    sectionalNodeClassName: 'section',
    controlNodeClassName: 'control',
    background: '#f4fa58'
  }, 'sectional_element');
  return true;
}

function putText() {
  document.getElementById('s').value = document.getElementById('text').textContent;  
  return true;
}

function sbmt() {
document.getElementById("searchform").submit();
}

(also I use jquery-1.8.3.js) The query should look like "mysite.com/search?q=". All that I need is to use div class="control" as Submit button instead of simple input (just replace the input button with div). When I press input button everything is ok, but when I use DIV class="control" submision doesn't work - form submits, but without text of query. I can't use just input, because the submit div is part of third party api.

Thanx for any suggestions.

Answer

Lyuben Todorov picture Lyuben Todorov · Mar 17, 2013

If you want to get the data inside the #text div you could use jQuery to get the data from the div:

function sbmt() {
  var param = '';

  // jQuery
  param = $('#text').text();

  // or you could use pure javascript
  param = document.getElementById('text').innerHTML;

  // Now that you have these values you should add them to your form as an input
  // input fields are how you send data through forms to wherever you are posting them
  // build the input field
  param = "<input type='text' name'param1' value='" + param + "'/>";

  // append it to the form
  $('#searchform').append(param);

  // finally submit the form.
  document.getElementById("searchform").submit();
}

Then you will be able to access your submited parameter based on the name you assigned it in the input field (in this case param1)

Have a play-around with this jsfiddle if you want to workout what is happening.