Passing edited value contenteditable field from vi

2019-02-24 19:47发布

问题:

I am using Rails 3.1 to build a web form which, among other fields, contains a table whose cells can be edited. I require to save the text of edited cell in a database.

I am thinking of using HTML5 attribute 'contenteditable'. I can use the value of innerHTML of the cell . How can I pass this value to Rails controller (from the view)? Is it possible to use params to pass the data? Any suggestions?

回答1:

HTML containers marked as contenteditable won't automatically be passed along to the server with a form submission, so you'll likely have to use javascript to pull the content out of those containers and pass them along in some fashion.

One strategy would be to add a handler to the form that fires before submit, which iterates over contenteditable containers and injects hidden form elements. The below example uses jQuery, but you could probably replicate the thought process without.

var form = $('#my_form');
var element;
$('[contenteditable=true]').each(function(){
  element = $(this);
  form.append($('<input/>', {
    type:'hidden',
    name:element.attr('id'),
    value:element.html()
  }));
});