synthax highlighter - editing the highlighted text in textarea element

282 Views Asked by At

I have implemented Alex Gorbatchev's Synthax highlighter, and it's working great, however when the user double clicks on the highlighted text(which by then became a div from textarea), it enters the edit mode(generates nameless textarea on the fly with highlited text data in it). I have created a button, and performing click event trying to grab the newly entered/edited text from it to rePOST it through ajax, but i keep getting either old text that was in textarea(which turned into a highlited div) or 'undefined'. I'm using jQuery to get the newly entered text but have no luck. Any help is greatly appreciated!

extends layout
block content
  h2=d.title
    a(class='button', href='/documents/' + d._id + '/edit') Edit
  p
    a(href='/documents', class='button')
      ← All Documents
  script(type="text/javascript")
    SyntaxHighlighter.all();
    SyntaxHighlighter.config.tagName = "textarea";

  form(name="form1") 
    div(style="width:800px; margin:0 auto; border: 2px grey solid;")  
      textarea(class="brush: js;", style="width:800px;", readonly="true", id = "srcText", disabled)
        =d.data || ''

  button(id="submit", class='button')

  script
    $("#submit").click(function (e) {
      console.log("boom");
      var dId = '#{d._id}';
      var dData = $("textarea").val(); // << -- problem here cant obtain the value
      console.log("DATA  is: ", dData);
      var updateDocumentIdPath = "/documents/" + dId + "/update";
      $.ajax({
        url: updateDocumentIdPath, 
        type: "POST",  
        data: {"data": dData},
        success: function (data) {
          console.log("success");
          console.log(data);
        },
        error: function () {
          console.log("error");
        },
        complete: function () {
        }
      }); // END ajax
    }); 
1

There are 1 best solutions below

1
On

For getting the data, you are using $("textarea").val(); which returns the value of the first textarea in the document. Docs: http://api.jquery.com/val/

What you need is something like: $("textarea:last").val();. This will return the value of the last textarea in the document. Assuming it will be the last textarea in the document since you mentioned its being dynamically inserted before switching to edit mode.