How to create single-line text input field? - javascript

I have contenteditable input field on my web page. What do I need to do to make it transform multi-line text into single-line, for example just like google does if you copy large amount of text into the search field?
Example - I copy such text:
This is Random text, lalalalalalala
and it's multi-line,
but that's just now what I want.
And when I paste it into my contenteditable input field, I want to get:
This is Random text, lalalalalalala and it's multi-line, but that's just now what I want.
-> entire text in one row

Use the following CSS on the element:
white-space:nowrap;

You should use the input tag like this: <input type="text"/>.

This is how I did it:
$('#paste').click(function(){
$(this).html('');
});
$('#paste').focusout(function(){
$(this).html($(this).text().replace('/n', ''));
});
Have a look at the full JSFiddle code demo

Use a text input. This is single line text field and will automatically remove line-breaks.
<input name="mySingleLineTextField" type="text" />
If you must use a textarea then you can easily format its value to remove tabs and line-breaks with a little bit of JavaScript:
<textarea name="myMultiLineTextFieldWithFormattingRemoved" onchange="this.value=this.value.replace(/([\n\r\t]+)/g, ' ')"></textarea>
eg: http://jsfiddle.net/z2rmxj4j/
As its not good form to put your scripts inline here's a little example that listens for a keyup event on all textareas that have the class 'nobreaks':
(function(){
//select all textareas having the class of 'nobreaks'
var elems = document.querySelectorAll("textarea.nobreaks");
//for each element in our collection
for(i=0; i<elems.length; i++){
//attach a function to the keyup event
elems[i].onkeyup = function(){
this.value=this.value.replace(/([\n\r\t\s]+)/g, ' ');
}
}
})()
pre {color:grey}
input, textarea {display:block; width:300px; margin:10px;}
.nobreaks {}
.nowrap {white-space:nowrap;}
<pre>This is Random text, lalalalalalala
and it's multi-line,
but that's just now what I want.
</pre>
<input type="text" value="Will replace line-breaks, text cannot wrap." />
<textarea>Default.
Wont replace line-breaks and text can wrap.</textarea>
<textarea class="nobreaks">Will replace line-breaks but text can still flow/wrap.</textarea>
<textarea class="nobreaks nowrap">Will replace line-breaks and prevent the text from wrapping.</textarea>
See https://developer.mozilla.org/en/docs/Web/HTML/Element/Input for more info on the input types.

var text = "This had line\n breaks\n in it.";
text = text.replace(/(\r\n|\n|\r)/gm,"");
alert(text);

Related

Convert HTML tags and display as styled text using javascript

I'm looking to design a form that will accept HTML tags and convert them into styled text displayed in a separate text area. Think a very simple JSbin. I thought that this would work:
document.getElementById('tagName').innerHTML='variable'
But this displays the text along with the tags - I just want the tag.
I need some helpful hints or a nudge in the direction I should go. Thanks!
Take a look at https://gomakethings.com/two-ways-to-get-and-set-html-content-with-vanilla-javascript/ you want to use .textContent to get the text without the tags.
document.getElementById('text').innerHTML=document.getElementById('html-elements').textContent
<div id="html-elements">
<button>hello</button> <strong><em>world</em></strong>
</div>
<div id="text"></div>
I think what you're looking for is contenteditable attr.
You can use that attribute in order to make editable a DOM element like div, span, p, and so on.
For more info go to Making content editable
On the order hand, to be able to write HTML from a textarea and the entered HTML text be rendered into the contenteditable element, you need to bind some kind of event in order to get the wrote HTML and then set it into the target contenteditable element.
var variable = '<b>EleFromStack</b>',
tagName = document.getElementById('tagName'),
textarea = document.getElementById('textarea');
textarea.addEventListener('input', function() {
tagName.innerHTML = this.value;
});
div {
width: 300px;
border: 1px dashed #000
}
<textarea id='textarea'>
</textarea>
<div id='tagName' contenteditable='true'>
</div>
I think what you want to do is create an input then listen to the value changes and display the inner html in another div
<!-- HTML -->
<input type="text" id="input"></input>
<div id="output"></div>
Then listen to the change and update the output
//JS
const input = document.querySelector('#input'),
output = document.querySelector('#output');
button.addEventListener('change', () => {
output.innerHTML = input.value;
})
(JSBIN: https://jsbin.com/genokox/edit?html,js,console,outputjsbin)
The problem is you're trying to write HTML into a text area. The text area is reserved, by the browser engine, to post plain text. Instead of writing out your content to a textarea write it to a DIV or some other content block designed to contain HTML.

Copy text and paste into a textarea using jquery

In a forum, I want to copy the original post and quote it and paste into a text area using jQuery:
I found this post. However, it doesn't apply what I really need.
If you have the original text in a <div> element like so:
<div id="original">
Original text...
</div>
and the button like so:
<button id="copy">Copy Text</button>
and the <textarea> like so:
<textarea id="paste"></textarea>
You can simply use jQuery to get the value of the original and paste it into the <textarea> like so:
$("#copy").click(function() {
$("#paste").val($("original").text());
});
See this example.
So, lets say you have the "original text" in a div with the ID original, the copy button has the ID copy, and the textarea has the ID paste-here. Then this simple snippet should to it:
//When the user clicks the copy button...
$('#copy').click(function() {
//Take the text of the div...
var text = $('#original').text();
//...and put it in the div:
$('#paste-here').val(text);
});
This will replace the content of the text area with the original text. If you just want to add it to the end, do this instead:
//Take the text of the textarea, a linebreak, and the text of the div...
var text = $('#paste-here').val() + '\n' + $('#original').text();
//...and put it in the div:
$('#paste-here').val(text);

Change <pre> block contents upon textarea update

I'm trying to get contents between the <pre>...</pre> tag to be rendered by JavaScript, where the contents is dynamic. What I hope to do is to type an input within a textarea to update display in the <pre> tags.
I'm unsure how to specify the contents within the <pre> tags to take the value from textarea on every textarea update.
Many Thanks!
Seeing the code you're working with would help greatly, but if I'm reading correctly, this should help. Assuming HTML like this:
<textarea id="type"></textarea>
<pre id="output"></pre>
This option uses pure javascript:
var textarea = document.getElementById('type'),
pre = document.getElementById('output');
if(textarea.addEventListener) {
textarea.addEventListener('keyup',function(){
pre.textContent = this.value;
});
} else {
textarea.attachEvent('onkeyup',function(){
pre.textContent = this.value;
});
}
This code block uses the jQuery library for brevity:
$('#type').on('keyup',function(){
$('#output').text($(this).val());
});
Note that in both situations, I am setting the text of the <pre>, not the HTML. This allows you to enter HTML characters like < into the textarea and have them be properly escaped in your <pre> element.
Pure JavaScript Demo
jQuery Demo
If you don't wish to change the <pre> until after you leave the <textarea>, then just change 'keyup' and 'onkeyup' to 'change' and 'onchange' respectively.
Bind the onchange event to the input, and then simply copy its value to pre:
<pre id="pre">Type something</pre>
<textarea id="text" rows="20" cols="20" />
​
<script type="text/javascript">
document.getElementById("text").onchange = function () {
document.getElementById("pre").innerHTML = this.value;
};
</script>
DEMO.​

How can I style text input as I type?

Every time I type a character in an input field, I parse the expression so that I get:
An array of tokens, i.e., tokenArray=[2, *, COS, (, 4, )]
A corresponding array of token types, i.e., tokenType=[NUMBER, OPERATOR, FUNCTION, (, NUMBER, )]
I need to style each token (for instance assigning a different color to each token) based on its respective token type.
I have been able to easily style a dynamic copy of the input text in a different <div> (not the input text itself, which is what I am asking for help) as follows:
JavaScript:
function processExpression() {
var userInput = document.getElementById('inputText').value;
var resultOutput = parse(userInput); //this generates the two arrays described above
for (i in tokenArray)
newHTML += "<span style='color: " + colorMap[ tokenType[i] ] + " '>" + tokenArray[i] + "</span>";
document.getElementById('styledExpression').innerHTML = newHTML;
}
HTML:
<input type="text" id="inputText" value="" placeholder="Type expression" size="40"
onKeyDown="processExpression();"
onKeyUp="processExpression();"/>
<div id="styledExpression" value=""></div>
How can I style the input text directly in the input field where I type?
Any JavaScript solution?
UPDATE
Tim's answer to the question replace innerHTML in contenteditable div provides some good help.
How would you modify http://jsfiddle.net/2rTA5/2/ to solve for when at every keydown, one reparses the entire editable? For example, imagine you type "=if(AND(3=2,A1:A4,OR(0,1)),5,6)" and, at every keydown the editable gets programmatically re-written (see token description above) and I lose the cursor.
How can this solution ignore the type of token or character or node and simply save and restore the absolute cursor (from the beginning of the ) position that was before the keydown?
Text inputs do not support styled content. End of story.
A common solution is to use contenteditable instead.
as Matt said, <input>s don't support styling content. However, one possible solution could be to use a second <span> that will contain the input's value, and show the styled content here. If that's not acceptable, then use contenteditable as Matt suggested.
You can sort of hack styling behind it if it's just for unimportant aesthetics.
Make the background and the text of the <input> transparent
Have another <span> behind it
Update the content of the <span> (with appropriate styling) when the <input>'s contents change
Here's a quick demo.

append div to text area?

I've got a text area and I'm attempting to append a div to it. I'm trying to do it with Jquery like this...
var text = '<div class="item"><a class="as">q</a>test</div>';
$('#textArea').append(text);
The code runs without throwing any errors but my text doesn't appear inside the textarea. Why does this happen?
Do you want to add it to the HTML structure or simply show the HTML Code as text ?
If you want to add it to the textarea HTML structure this will not work.
What you are searching for is
$('#textArea').text(text); or $('#textArea').text($('#textArea').text()+text);
.text() sets text of your textArea
.html() would set your html Content
You can't append to a textarea. Its text content behaves like other input.
var text = '<div class="item"><a class="as">q</a>test</div>';
$('#textArea').val( $('#textArea').val() + text);
Try:
$('#textArea').val(text);
If you don't want to render the div's contents but simply want to display the HTML inside the textarea you need to convert the HTML first:
var lt='<';
var gt='>';
var text = '<div class="item"><a class="as">q</a>test</div>';
text = text.replace(/</gi, lt);
text = text.replace(/>/gi, gt);
$('#textArea').append(text);
And the HTML for the text area should look like this:
<textarea id="textArea"></textarea>
If you do want to render the div's contents inside the textarea use:
var text = '<div class="item"><a class="as">q</a>test</div>';
$('#textArea').append(text);
The HTML for the text area is the same as in the other example:
<textarea id="textArea"></textarea>
You cannot put div in textarea but sometimes you need to do so. Good news is that you can do it in other way by using contenteditable property of elements. Like
<div contenteditable="true" style="min-height:50px; width:300px;" id="txtDiv">
</div>
This Div will behave exactly like a Textarea but you can append anything you want. And remember when you want to grab data from inside it in jquery
var ContentofDiv = $('#txtDiv').html();

Categories