how to make enter on input show up on output [duplicate] - javascript

This question already has answers here:
angularjs newline filter with no other html
(7 answers)
Closed 6 years ago.
When the user presses enter in the input box I would like that to reflect in the H1 tag.
As you can see when the user types
Line 1
they can press enter and create
line 2 in the input no problem, but the output in the h1 tag is still "Line 1 line 2" all on one line.
Please look at the fiddle as that will make a lot more sense.
I was thinking about using a keypress function to get when the user presses enter and then do something with that? I'm not sure if there is a better way though.
https://jsfiddle.net/BSmyth634/ovz8thrp/
<div ng-app>
<form>
<textarea rows="4" type="text" ng-model="todoText" size="30" placeholder="add new todo here">
</textarea>
</form>
<h1>
{{todoText || 'Hello World'}}
</h1>
</div>

You need to use style="white-space: pre;" in your code to do it.
JS Fiddle

I see two ways to achieve what you want.
Use white-space css property. In your case the pre-line value might be interesting.
Create Angular's filter and use it.

you can use pre element instead of h1
<pre>{{todoText || 'Hello World'}}</pre>
or use this
<h1 ng-repeat="line in todoText.split('\n')">
{{line}}
</h1>

Jquery approach
$("textarea").on('keypress',function(e){
if(e.keyCode == 13){
$('h1').html($("textarea").val())
}
})

Related

Why does JQuery .val() method sometimes return undefined when code is valid? [duplicate]

This question already has answers here:
val() vs. text() for textarea
(2 answers)
Closed 4 years ago.
Not a duplicate question; so please consider the content closely before presumption.
I've been using JQuery for years and have never seen this type of behavior before. Consider the following:
<html>
<div class="order-form-group">
<label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
<textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
</div>
<div class="order-form-group">
<label class="order-form-label" for="guestReason">Reason:</label>
<textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
</div>
<div class="button-container">
<input class="order-form-submit" type="submit" value="Submit">
</div>
</html>
I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as
having the incorrect selector, having more than 1 id on the page and etc.
<script>
var specInstr = $("#guestSpecialInstructions").val();
var guestReason = $("#guestReason").val();
</script>
I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.
The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.
After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:
<script>
var specInstr = $("#guestSpecialInstructions")[0].value;
var guestReason = $("#guestReason")[0].value;
</script>
Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.
Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.
If I need to change the wording of the title, let me know.
You can only use text() on a <textarea> if it is pre-populated and to return the original content
Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content
Always use val() to get and set
var $txt = $('textarea')
console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())
$txt.val( 'Some new content')
console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
Original text
</textarea>

Limit number of lines able to write with textarea

I want to not just limit the number of times enter can be pressed in the text area but stop the output being over two lines. To better explain, I have a photo frame designer here. In the options you can enter text and it will appear on the frame. Currently if you try to press enter in text area more than 2 times it won't let you. The problem arises when the text is too long and it automatically wraps to a new line.
Here is some relevant code.
$(document).ready(function(){
var lines = 2;
var linesUsed = $('#linesUsed');
$('#input').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
return false;
}
});
});
That's some jquery that limits the number of lines in the TEXTAREA.
And the textarea
<textarea id="input" maxlength="40" name="Text" value="Max. 40 characters"></textarea>
The jquery that prints the input from the text area
$('#input').keyup(function() {
$('#text').html($(this).val());
});
This is the embedded html in my svg where the typed text is printed to.
<foreignObject x="135" y="520" width="600" height="260" style="color:white;text-align:center">
<body xmlns="http://www.w3.org/1999/xhtml">
<div id="container2">
<p id="text">Your words here</p>
</div>
</body>
</foreignObject>
Automatic line wrapping in a textarea can be prevented using the attribute wrap=off, which is nonstandard but widely supported since the early days of HTML.
<textarea id="input" maxlength="40" name="Text"
placeholder="Max. 40 characters" wrap="off"></textarea>
(I have changed the value attribute to a placeholder attribute. The value attribute is not valid for textarea.)
A different, possibly better approach is to avoid the problem by using two input type=text fields instead of one textarea field. Then you would not need JavaScript for preventing the entry of more than two lines, but if a limit on the total number of characters (instead of just setting a limit on each line) is needed, you would need simple JavaScript for that.
Here are 2 javascript libraries that can help you with this:
Stop Verbosity
Limit
As you can see on the demo-sites, both these solutions just work.

Escape HTML tag in <textarea>

I have one <textarea> tag in my website where the user can put there HTML code and see its preview. My problem is when the user enter code below mention in my <textarea> my preview functionality getting fail :
<html>
<textarea>Some code to show</textarea>
</html>
So question is how can I escape this html code in my <textarea> tag as I know the problem is coming because </textarea> tag.
Any solution on this please.
Edit
Question is about using </textarea> within a textarea.
Problem visible here: http://jsfiddle.net/hrP6F/
EDIT: for your purpose this would do:
<textarea>
Outside Textarea
<textarea>Inside Textarea</textarea>
</textarea>
source: How can I embed a textarea inside of another textarea in HTML?
Or use contenteditable like someone already mentioned -> click
FIRST ANSWER: Im not sure I understand perfectly but still. You want to display the code inside text area somewhere else for instance?
You could do that on click like this (I reckon you are not statically putting nested text areas in html?):
HTML:
<textarea id="textarea" >Something code to show</textarea>
<button onclick="show()">show</button>
<div id="showArea"></div>
JS:
function show(){
var t = document.getElementById('textarea').value;
document.getElementById('showArea').innerHTML = t;
}
This is of course if what you want is to display html that is inside textarea. you could also put another textarea inside first one and it will work.
If you want the results to display dynamically you could use
<textarea id="textarea" onkeyup="show()">Something code to show</textarea>
This works even if you put your code (html and text area) inside text area - it displays it, I tested it
You can add a output div for preview purpose. Below is the jQuery script
HTML
<textarea placeholder="Enter your html"><b>test</b></textarea>
Run
<div class="op"></div>
JS
$('.run').click(function(){
$('.op').html($('textarea').val());
return false;
});
DEMO

jquery to take in the typed text in a textarea and pass it to a backend handler (perl, php, etc..)

I have a very simple 'textarea' in html:
<div id="textarea">
<textarea rows="20" cols="45" autofocus wrap>
</textarea>
</div>
With 2 buttons:
<div class="buttonbox">
<a class="button" href="#"><span id="spButton">Solve Problems</span></a>
<a class="button" href="#"><span id="pmfButton">Pull My Finger</span></a>
</div>
I am trying to understand the jQuery to allow the button 'spButton', when pressed following text entered into the 'textarea', to be captured and passed, in a var to the backend, in my case perl. I have seen/tested some XHR handler cases for image transfer, and they work fine, but thought that simple text would be far more... well... simple? I am not able to grab the typed text at all, only the static text that I had placed within the 'textarea' tags? Clearly I am missing something.
In the following attempt, I am not able to extract the 'var' to even print the text entered in an alert:
$(function() {
$('#spButton').click(function() {
var inText = $('textarea#textarea').val();
alert(inText);
});
});
The above, while appearing to be syntactically(questionable) correct, does not return any typed text from the 'textarea' to the alert, it is simply a bank alert popup with 'undefined' as the text? I have also tried '.text()' however that only grabs any text encapsulated within the 'textarea' tags. You can get a look at what I have done so far (very little) here: https://github.com/gmconklin/zephyr
Apparently I need a rep to post pics? Hmm nonsensical, but I cannot provide screenshots due to this limitation, apologies.
Thanks for any assistance.
-G
When you write:
var inText = $('textarea#textarea').val();
That means a textarea with id textarea.
What you want is a textarea inside a div with id textarea. That is this:
var inText = $('#textarea textarea').val();

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

Categories