mercredi 11 février 2015

jQuery post causes loss of carriage returns in a Rails 3.2 app


I have a simple form that inserts different types of footnotes into the body of the text. I'll put one of the clickable types below.



<%= simple_form_for(@tut_text) do |f| %>
<%= f.input :content, :input_html => {:class => 'w80pct', :id => "#{@tut_text.id}"} %>
<%= f.button :submit, 'Update Tutorial Text', :class => 'btn btn-primary btn-large' %>
<% end %>

<h4>Add Footnotes:</h4>
<a href="#" onclick="insertFootnoteMarker('<%= @tut_text.id %>','&reg;', 'page');return false;">
Registered Trademark:<span class = "foot">&reg;</span>
</a>


Clicking the link for the footnote causes the following jQuery function to access the textarea and inserts the footnote marker where the caret/cursor is.



function insertFootnoteMarker(areaId,text,reload) {
$("#spinner").show();
var text = text+"~"
var reload = reload
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false ) );

if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
strPos = range.text.length;
}
else if (br == "ff") strPos = txtarea.selectionStart;

var front = (txtarea.value).substring(0,strPos);
var back = (txtarea.value).substring(strPos,txtarea.value.length);
txtarea.value=front+text+back;
alert(txtarea.value);
var url = "/tut_texts/" + areaId + "/" + "new_footnote/?content=" + txtarea.value;

$.post(url, areaId, function(html) {
if (reload === 'page') {
window.location.reload(true);
} else {
$("#spinner").hide();
};
});
}


Note the alert. In the alert, the carriage returns are retained. Here is the controller action to which the content is posted:



def new_footnote
@tut_footnote = TutFootnote.create(:tut_text_id => params[:id])
content = params[:content]
position = content.index('~')
front = content.slice(0,position)
back = content.slice(position + 1, content.length)
content = front + @tut_footnote.id.to_s + back
@tut_text = TutText.find(params[:id])
@tut_text.update_attributes(:content => params[:content])
render :nothing => true
end


Content in the textarea before adding the footnote:


Paragraph1


Paragraph2


Paragraph3


Content in the textarea after adding the footnote:


Paragraph1Paragraph2®~Paragraph3


Thanks for your help.





Aucun commentaire:

Enregistrer un commentaire