Include space from input - javascript

My user wants an input field where he can enter a message, which I will then have displayed as a scrolling marquee across the page. He wants to be able to include empty spaces, for example,
"Employees please look up."
My textarea, when I get the text, doesn't notice the space. Any way to get that?
I know this is an odd request - google only tells me how to remove whitespace, not include it.
var text = $('textarea').val();
<textarea class='messageInput'></textarea>

I am pretty sure that you are getting the value with all the white-spaces right, the problem is in the displaying of the value in your (probably) custom div. The best way would be to set white-space: pre on that element which (as the option suggests) will preserve white-space. ;) Example:
<div id="foo" style="white-space: pre"><!-- insert text here --></div>
And ignore all the &nbps; suggestions which are essentially modifying the text content. CSS is the right way to do this!

You need to convert space characters into non-breaking spaces, which can be done using String.prototype.replace() with a regular expression:
$('#text').html($('textarea').val().replace(/ /g, '&nbsp'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='messageInput'>employees hello</textarea>
<p id="text"></p>
You need / /g so that it will match all spaces, not just the first one, which .replace(' '...) would do.
Note that smajl's suggestion is less invasive and probably better, but I'll leave this for posterity.

The spaces in the value are not ignored. It's that the browser by default "compresses" duplicate spaces. Use white-space:pre;
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
document.getElementById("button").onclick = function() {
var content = document.getElementById("input").value;
console.log(content);
document.getElementById("result").innerHTML = content;
}
#result {
white-space:pre;
}
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
EDIT: too late ;)

Related

Removing whitespace in textarea ignored by jQuery.trim()

I have a <textarea> which contains a text called by php. The text contains an ID of the user, so it's for every user different. However, the html looks always like this:
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>
How do I remove these whitespaces. I have tried multiple trim suggestions or Regex approaches on SO, but none of them are working. The textarea cannot be changed into a div or p.
Update:
Regex is somehow ignored, but the below answer gave the outcome:
$("#text").val((i, v) => '${v.slice(1, -1).trim()}');
Use regex pattern /\s{2,}/g in .replace() that match multiple spaces and remove them from string.
$("#text").val((i, v) => v.replace(/\s{2,}/g, ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>
Also you can remove " from start and end of string using String.slice() and then remove space using .trim(). At the end wrap string with ""
$("#text").val((i, v) => `"${v.slice(1, -1).trim()}"`);
You can use a regex to remove quotes and spaces
$("#text").val($("#text").val().replace(/^"\s+(.*?)\s+"$/,"$1"));
console.log(">"+$("#text").val()+"<")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>

How can I make HTML code non-execute?

What I want to do is allow the user to input a string then display that string in the web page inside a div element, but I don't want the user to be able to add a bold tag or anything that would actually make the HTML text bold. How could I make it so the text entered by the user does not get converted into HTML code, if the text has an HTML tag in it?
Use createTextNode(value) and append it to your element(Standard solution) or innerText(Non standard solution) instead of innerHTML.
For a JQuery solution look at Dan Weber's answer.
here's a neat little function to sanitize untrusted text:
function sanitize(ht){ // tested in ff, ch, ie9+
return new Option(ht).innerHTML;
}
example input/output:
sanitize(" Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World");
// == " Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World"
It will achieve the same results as setting elm.textContent=str;, but as a function, you can use it easier inline, like to run markdown after you sanitize() so that you can pretty-format input (eg. linking URLs) without running arbitrary HTML from the user.
use .text() when setting the text in the div rather than .HTML. This will render it as text instead of html.
$(document).ready(function() {
// Handler for .ready() called.
$("#change-it").click(function() {
var userLink = $('#usr-input').val().replace(/.*?:\/\//g, "");
$('#users-text').text(userLink);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="form-control" id="usr-input">
<br>
<button id="change-it" type="button">Update Text</button>
<br>
<div id="users-text"></div>
Why not simply use .text() ?
$('#in').on('keyup', function(e) {
$('#out').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="in">
<br>
<div id="out"></div>

how to remove <textarea> whitespace

I want a <textarea>, as the one I'm writing in right now actually.
How do I make the textarea behave like this one? I want it to start at the beginning and not give me whitespace to erase when clicking in the middle of it.
HTML
<p>
<textarea class="noteToAdd">
</textarea>
</p>
Any ideas?
That what is between the start tag <textarea> and end tag </textarea> is it's value. Even whitespace is seen as 'value'. You probably have something like this: (note the whitespace)
<textarea>
</textarea>
So, to remove that, remove all whitespace and place the start and ending tag directly after each other.
<textarea></textarea>
Remove your whitespace between the textarea tag. Like as
<textarea></textarea>
Try this one :
<p>
<textarea class="noteToAdd">
</textarea>
</p>
Make sure there is no whitespace between your <textarea> and </textarea> tags, any whitespace here will show up in your text area.
More help is not possible without you providing the HTML/CSS.
Remove the extra white space in between the textarea opening and closing tags as they take up that space. You write your content inside <textarea></textarea>
<p>
<textarea class="noteToAdd"></textarea>
</p>

Jquery text search and do something with that text

I am trying to get something that looks through a div with an id of 'Holder' and searches for a string. Preferably this string would be case-insensitive. This string would be have an input connected (variable is 'Terms'). Once the code has found all the paragraphs that have the string, add a class to them called 'Found'. I do not have that much knowledge with Jquery (just the very basics) so if anyone could help me, that would be fantastic!
Code so far:
<!DOCTYPE html>
</html>
<body>
<p id="header">Searcher</p>
<hr>
<p id="form">
<input autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase">
<button type="button" id="sea" onClick="Search ()">Search</button>
<br>
</p>
<div id="Holder">
<p id="Note">This is a test paragraph uses to test.</p>
<p id="Note">For jquery. I want to search for this paragraph using "for jquery".</p>
</div>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="test.js">
</script>
</body>
Here is a working code sample. You should read the comments because I made a few changes to how you were doing things in order to improve code quality. There is still more that could be done (like using a real form), but this should get you pointed in the right direction. If my comments aren't clear, feel free to ask why I made the changes that I did and I'll try to provide a better explanation.
<html>
<style>
.match-found {
background: yellow;
}
</style>
<body>
<p id="header">Searcher</p>
<hr>
<p id="form">
<!--
You should use a real form and attach to the submit handler, but I
feel the need to leave something as an exercise for the reader
-->
<input autocomplete="off" id="bar" name="input" type="text" placeholder="Search for word or phrase">
<button type="button" class="search-text" data-search-target="#holder">Search</button>
<br>
</p>
<div id="holder">
<p id="note">This is a test paragraph uses to test.</p>
<p id="note">For jquery. I want to search for this paragraph using "for jquery".</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function search(searchTarget, term) {
// lowercase terms because uppercase should be reserved for constructors
// also made it singular because we're looking for an exact match, not
// a list several separate terms.
// (if I understand your problem description correctly)
term = term.toLowerCase();
// If you're searching for simple terms, regex would be better,
// but since I'm not sure how you'll actually be using this,
// lowercasing the string and searching for a containing string will
// provide more consistent results because we won't have to worry about
// escaping special characters and the like.
$(searchTarget).find('p').each(function() {
var searchText = $(this).text().toLowerCase();
if (searchText.indexOf(term) !== -1) $(this).addClass('match-found');
// match-found is more descriptive that 'found'.
// Also avoiding caps again because capitilization has specific meaning
});
}
// A better way to attach event listeners
$(document).ready(function() {
$('.search-text').click(function() {
var searchTarget = $(this).attr('data-search-target');
var searchText = $('#bar').val();
search(searchTarget, searchText);
});
});
</script>
</body>
</html>
$("#sea").on("click", function() {
$("#Holder > p:contains('" + $("#Bar").val() + "')").addClass("found");
});
The above code attaches a click event to the search button #sea. Using the :contains() selector it searches all <p> tags which are direct children of #Holder for the value of #Bar and adds the class "found".
https://jsfiddle.net/mz0ge2w8/1/

How to validate or wrap user inputted HTML to fix unclosed tags

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>

Categories

Resources