I have a concern how to get the string from textarea but also to get every new row added by pressing enter, also TAB space. Priority is to get every new row, so I can use that string to add to paragraphs but to respect new rows, TAB spaces.
Example:
Textarea text: http://prntscr.com/kvbbcv.
When I add value to the paragraph:
http://prntscr.com/kvbbur
One more example: http://prntscr.com/kvhmca
What would be the best practice to fix this problem?
Code:
<textarea v-model="comment"></textarea>
<p>{{ comment }}</p>
I found the solution to resolve this problem.
The solution is to use <div contenteditable></div> and get the value from this <div> when content inside of it is changed using #input="contentEditableChange()"
The function will return the value as HTML. But using v-html you can convert html string to html preview.
So final solution code is:
<div id="unique-element" #input="contentEditableChange()" contenteditable></div>
<p v-html="message"></p>
Method:
contentEditableChange() {
this.message = document.getElementById("unique-element").innerHTML;
},
if you using ckeditor, you can try like this
<ckeditor v-model="comment"></ckeditor>
<p v-html>{{comment}}</p>
because ckeditor has added new lines automatically. or if you use textarea, add a <br> tag manually.
Related
I have the below code for generating comments (cutted down for simplicity sake):
<div v-for="(g, gi) in submission.goals" :key="gi">
<div>
<p >Goal #{{gi+1}}</p>
<div>{{g.text}}</div>
</div>
<div>
<p>Comments:</p>
<div><span class="uk-text-small uk-text-muted"><i>no comments</i></span></div>
<hr>
<div>
<textarea class="comment-input" placeholder="type your comment here"></textarea>
</div>
</div>
</div>
and my method look like this:
submitComment(gid,uid,phase,e)
{
e.preventDefault();
//var comment -> get the value of the closes textaraea here
console.log(gid, uid, phase, comment);
//here I will make the ajax call to the API
}
As you can see the whole thing is generated in a v-for loop generating divs according to the size of the submission.goals array returned by the API.
My question is how can I get the value from the textarea input closest to the anchor that is calling the submit function.
Obviously I can't have a separate data object for each comment area since I do not have a control over the size of submission.goals array. And if I use v-model="comment" on each input, whatever user types in will be automatically propagated to each and every textarea.
I know how to handle this with jQuery, but with Vue.js I am still in the early learning stages.
If you mark the text area as a ref, you could have a list of textarea elements. With the index number of the v-for items (gi in your case), you can get the [gi] element of the refs list and submit its value.
<textarea ref="comment" class="comment-input" placeholder="type your comment here"></textarea>
submitComment(gid,uid,phase,e, gi)
{
e.preventDefault();
var comment = this.$refs.comment[gi].value;
console.log(gid, uid, phase, comment);
//here I will make the ajax call to the API
}
Try change submission.goals to computed submissionGoals and create this computed with the code above:
submissionGoals(){
return this.submission.goals.map(goal => ({...goal, comment: ''}));
}
Use v-model="g.comment" on textarea.
Now change submitComment(g.id, g.user_id, g.phase, $event) to submitComment(g, $event) like Alexander Yakushev sayed.
In angularjs, how to get the exact text as entered into html textarea, I want to also track newlines, '\n' (in the textarea). I want to store this textarea into database exactly the same as entered into textarea. But it is taking all text into one line.
How do I detect that new line is inserted into html-area?
Please see the demo
I can use <pre> {{someText}}</pre>, but this will not solve my problem, Because I want to store into database.
<div class="col-md-12">
<div class="col-md-6">
<label >Location Based Address </label>
<textarea rows="4" cols="25" class="form-control" ng-model="someText">
</textarea>
</div>
</div>
I belive that the model does save newlines and such, see this small edit on your plunkr, using a <pre> tag to display the data.
Also, when I save data to my SharePoint list, in a 'rich text' field, it saves newlines. I think your problem is that the server doesn't preserve the new lines.
Please check i have edited your plunker code. Check updated code
angular.module('app', ['ngSanitize'])
.controller('SomeController', function($scope,$sce) {
console.log($scope.someText);
$scope.$watch('someText', function(){
console.log($scope.someText);
$scope.text = $scope.someText;
$scope.text = $scope.text.replace(/\n\r?/g, '<br />');
$sce.trustAsHtml($scope.text)
})
})
Hope this will help you.
You could replace spaces with \n and store it that way, but I'm not sure how 'strong' this solution will be.
Value from the textarea is passed as is to someText via ng-model="someText". You don't need to do anything with the text as you can see in console.
If you want to print the value somewhere on your page while keeping new lines as the user entered them use <pre> tag:
<pre>{{ someText }}</pre>
Well i'm not really sure of what is happening but i'll try a wild guess of all things that can happens :
When using textarea, \n characters are stored in the value of the ng-model.
If you want to display them either use <pre> or replace all \n by and use ng-bind-html (https://docs.angularjs.org/#!/api/ng/directive/ngBindHtml)
If you want to send them to the server through json you may have to escape \n to \n same when sending data from the server to the client. Or it will be the underlying layers off your framework that will do it.
Make sure you're working with UTF-8 server-side/database or you may have problems with \r\n and \n.
I have text boxes in a form where users can input formatted text or raw HTML. It all works fine, however is a user doesn't close a tag (like a bold tag), then it ruins all HTML formatting after it (it all becomes bold).
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
You may try jquery-clean
$.htmlClean($myContent);
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
Yes: When the user is done editing the text area, you can parse what they've written using the browser, then get an HTML version of the parsed result from the browser:
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
Live example — type an unclosed tag in and click the button:
$("input[type=button]").on("click", function() {
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
$(document.body).append("<p>You wrote:</p><hr>" + html + "<hr>End of what you wrote.");
});
<p>Type something unclosed here:</p>
<textarea id="the-textarea" rows="5" cols="40"></textarea>
<br><input type="button" value="Click when ready">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Important Note: If you're going to store what they write and then display it to anyone else, there is no client-side solution, including the above, which is safe. Instead, you must use a server-side solution to "sanitize" the HTML you get from them, to remove (for instance) malicious content, etc. All the above does is help you get mostly-well-formed markup, not safe markup.
Even if you're just displaying it to them, it would still be best to sanitize it, since they can work around any client-side pre-processing you do.
You could try and use : http://ejohn.org/blog/pure-javascript-html-parser/ .
But if the user is entering the html by hand you could just check to have all tags closed properly. If not, just display an error message to the user.
You can create a jQuery element using the text and then get it's html, like so
Sample
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
Script
alert($($('textarea').text()).html());
alert($($('textarea').text()).html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
The simple way to check if entered HTML is actually valid and parseable by browser is to let browser try it out itself using DOMParser. Then you could check if result is ok or not:
function checkHTML(html) {
var dom = new DOMParser().parseFromString(html, "text/xml");
return dom.documentElement.childNodes[0].nodeName !== 'parsererror';
}
$('button').click(function() {
var html = $('textarea').val();
var isValid = checkHTML(html);console.log(isValid)
$('div').html(isValid ? html : 'HTML is not valid!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="80" rows="7"><div>Some HTML</textarea> <button style="vertical-align:top">Check</button>
<div></div>
Not sure if this is an actual problem per se but I'm using Epic Editor to input and save markdown in my GAE application (webpy with mako as the templating engine).
I've got a hidden input element in the form which gets populated by the EpicEditor's content when I submit the form but all the white spaces are replaced by . Is this an intended feature? If I check the same code on the EpicEditor site, it clearly returns spaces instead of so what's different about mine?
<form>
<!-- form elements -->
<input id="content" name="content" type="hidden" value></input>
<div id="epiceditor"></div>
<button type="submit" name="submit" id="submit">submit</button>
</form>
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML; //all the spaces are returned as and breaks are <br>
$('input#content').html(content);
});
</script>
NOTE: I want to save my content as markdown in a TextProperty field my data store and generate the html tags when I retrieve it using marked.js
I'm the creator of EpicEditor. You shouldn't be getting the innerHTML. EpicEditor does nothing to the innerHTML as you write. The text and code you are seeing will be different between all the browsers and it's how contenteditable fields work. For example, some browsers insert UTF-8 characters for spaces some  .
EpicEditor gives you methods to normalize the text tho. You shouldn't ever be trying to parse the text manually.
$('button#submit').click(function(){
var content = editor.exportFile();
$('input#content').html(content);
});
More details on exportFile: http://epiceditor.com/#exportfilefilenametype
P.S. You don't need to do input#content. Thats the same as just #content :)
You can do this if you dont find out why:
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML;
content = content.replace(" ", " ");
$('input#content').html(content);
});
</script>
[EDIT: solved]
I shouldn't be using innerHTML, but innerText instead.
I figured out that Epic Editor uses on all spaces proceeding the first one. This is a feature, presumably.
However that wasn't the problem. ALL the spaces were being converted to , eventually, I realised it occurs when Epic Editor loads the autosaved content from localStorage.
I'm now loading content from my backend every time instead of autosaving. Not optimal, but solves it.
i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/