How do I make an expanding textbox? - javascript

I want to make a textbook where it starts out as a given width/height. Then if users type more then the given amount of space, the textbox expands downward. How do I go about doing this? Do I use CSS?
The basic textbox just displays a scroll bar when users pass the number of rows allow. How do I make it so the textbox expands the rows by say 5 more?
<form method="post" action="">
<textarea name="comments" cols="50" rows="5"></textarea><br>
<input type="submit" value="Submit" />
</form>
How do I use the example that Robert Harvey mentioned? I never used JavaScript before..

jQuery AutoResize Plugin
http://james.padolsey.com/javascript/jquery-plugin-autoresize/
Steps to use:
You need jQuery. To add it to your page:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
Then, download the plugin and put it in the same folder as your web page. To reference it, add this to your web page:
<script type="text/javascript"
src="autoresize.jquery.js"></script>
Next, add a textbox to your page:
<textarea id="comment" style="width: 400px; padding: 10px; height: 50px;
display: block; font-family:Sans-serif; font-size:1.2em;">
Type something in here, when you get close to the end the box will expand!
</textarea>
Finally, in a script block, add the code that hooks up the plugin to the textbox:
<script type="text/javascript">
$('textarea#comment').autoResize({
// On resize:
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
// Quite slow animation:
animateDuration : 300,
// More extra space:
extraSpace : 40
});
</script>

You can add a library if you care to, or just keep track of the textarea's scrollTop property.
If scrollTop is not zero, add your rows.
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title>Expand textarea </title>
<style>
textarea{overflow-y:scroll}
</style>
<script>
onload=function(){
var who=document.getElementsByName('comments')[0];
who.onkeyup=function(){
if(who.scrollTop)who.rows=parseInt(who.rows)+5;
}
}
</script>
</head>
<body>
<textarea name="comments" cols="50" rows="5"></textarea>
</body>
</html>

Here is my solution using only vanilla javascript.
Tested to work in Chrome, Firefox & IE8 and up.
On load, or whack it in a function:
var element = document.getElementById('comments');
var retractsAutomatically = false;
var sizeOfOne = element.clientHeight;
element.rows = 2;
var sizeOfExtra = element.clientHeight - sizeOfOne;
element.rows = 1;
var resize = function() {
var length = element.scrollHeight;
if (retractsAutomatically) {
if (element.clientHeight == length)
return;
}
else {
element.rows = 1;
length = element.scrollHeight;
}
element.rows = 1 + (length - sizeOfOne) / sizeOfExtra;
};
//modern
if (element.addEventListener)
element.addEventListener('input', resize, false);
//IE8
else {
element.attachEvent('onpropertychange', resize)
retractsAutomaticaly = true;
}
CSS & HTML:
textarea#comments { overflow:hidden; }
<textarea id="comments" cols="50" rows="1"></textarea>

Related

Is there a way to stop html from making line breaks when a tag is in another tag?

So I would like to make a calculator with some formatting to make it look nice. It keeps making a new line for my p tag and I don't want it to, is there any fix for this?
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var display = document.getElementById("disp");
function addAndDisplay() {
display.innerHTML = (Number(n1.value)+Number(n2.value)).toString();
}
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<h3>Value one:</h3>
<input type="number" id="n1">
<h3>Value two:</h3>
<input type="number" id="n2">
<br>
<button onclick="addAndDisplay()">Add</button>
<h3>The output: <p id="disp">You have not calculated anything yet</p>.</h3>
</body>
</html>
EDIT: Thanks #Pipe and #Pointy I appreciate your help a lot!
Per default, a paragraph is a block level element. This means that it starts on a new line and takes up the full width. Maybe you should consider using something else.
For this kind of usecase, you would want to use <span></span>. Span is using display: inline which allows multiple inline-elements to appear next to each other.
It might be useful to read this article about the CSS display property - it will help you understand the suggested solution much better.
you shuld use span instead of p. p is paragraph element and span can be used to group elements for styling purposes
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var display = document.getElementById("disp");
function addAndDisplay() {
display.innerHTML = (Number(n1.value)+Number(n2.value)).toString();
}
p{
display:inline-block;}
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<h3>Value one:</h3>
<input type="number" id="n1">
<h3>Value two:</h3>
<input type="number" id="n2">
<br>
<button onclick="addAndDisplay()">Add</button>
<h3>The output: <p id="disp">You have not calculated anything yet</p>.</h3>
</body>
</html>

My JQuery post data to 'textbox' how to post it to 'div'?

I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.
here's my code
<div id="result" style="display:none;">
<div class="col-sm-5 text-right"><label>Participant fee (IDR):</label></div>
<div class="col-sm-7"id="parcost" ></div>
<div class="col-sm-5 text-right"><label>Populi fee (IDR):</label></div>
<div class="col-sm-7"><input type="text" id="popcost"></div>
<div class="col-sm-5 text-right"><label>Total Estimated Cost (IDR):</label></div>
<div class="col-sm-7"><input type="text" id="totcost"></div>
</div>
$(document).ready(function(){
$('#calc').click(function(){
var num_participant = parseInt($("num_participant").val());
var reward = parseInt($("reward").val());
var esttime = parseInt($("esttime").val());
var parcost = num_participant*reward;
var popcost = (parcost*0.1)+(num_participant*150);
var totcost = parcost+popcost;
/*
document.getElementById("result").style.display = "block";
document.getElementById("parcost").value = parcost;
document.getElementById("popcost").value = popcost;
document.getElementById("totcost").value = totcost;*/
document.getElementById("result").style.display = "block";
$("#parcost").html(parcost);
$("#popcost").html(popcost);
$("#totcost").html(totcost);
return false;
});
});
Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".
any ideas?
I'm not sure if you're asking this but try something like this,
var totCost = document.getElementById("totcost").value;
$("#yourDivID").html(totCost);
I'm not sure what you are asking about but if you want to send the result to a div, just use $("#divId").html(result)
I think that you must use .text or .html in place .value.
look at this example using jquery:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p {
color: blue;
margin: 8px;
}
b {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><b>Test</b> Paragraph.</p>
<p></p>
<script>
var str = $( "p:first" ).text();
$( "p:last" ).html( str );
</script>
</body>
</html>
If you wish to add a result in a div try with:
jQuery("#divID").append("<p>" + data + "<p>");
To update the content of a <div> or <p> element, you would use innerHTML instead of value.
So in your sample code you would update this line:
document.getElementById("parcost").value = parcost;
into this:
document.getElementById("parcost").innerHTML= parcost;
Furthemore, since you are already using jQuery, you can simplify your click function:
$('#calc').click(function(){
var num_participant = parseInt($("#num_participant").val());
var reward = parseInt($("#reward").val());
var esttime = parseInt($("#esttime").val());
var parcost = num_participant*reward;
var popcost = (parcost*0.1)+(num_participant*150);
var totcost = parcost+popcost;
$("#result").css("display", "block");
$("#parcost").html(parcost);
$("#popcost").val(popcost);
$("#totcost").val(totcost);
});

JQuery line numbers on Textarea with wrapping support

I am working on a textarea with line numbers. Now I found a great little script. http://jakiestfu.github.io/Behave.js/
Demo here: http://jakiestfu.github.io/Behave.js/examples/example-hook-linenums.html
The one feature I am missing is the ability to enable line wrapping.
Of course I can add wrap="on" to the textarea, and that indeed offers wrapping, but the line numbers are then messed up.
Any idea how I could add support for wrapping whist keeping the line numbers correct?
Try this:
<!DOCTYPE html>
<html>
<body onload="keyDown()">
<div class="container" style="width:300px;">
<div id="numbers" style="float:left; background:gray; width:20px;"></div>
<textarea onkeypress="keyDown()" rows="1" style="line-height:20px; display:block; float:right; overflow:hidden;" id="ta"></textarea>
</div>
<script type="text/javascript">
function keyDown(){
var taLineHeight = 20; // This should match the line-height in the CSS
var taHeight = ta.scrollHeight; // Get the scroll height of the textarea
ta.style.height = taHeight + "px"; // This line is optional, I included it so you can more easily count the lines in an expanded textarea
var numberOfLines = Math.floor(taHeight/taLineHeight);
var inner= "";
for(var i=1; i<=numberOfLines; i++)
inner += "<div>"+i+"</div>";
document.getElementById("numbers").innerHTML = inner;
}
</script>
</body></html>

Prevent backspacing HTML in an iFrame.

I am using an iFrame as a text editor and want to ensure that the first part of the body is always a p tag. As such, I have it set so when users first click on the body it will insert
<p><br></p>
This works, unless the user holds down the backspace button. Once the user runs out of plaintext to backspace, it removes the tags above.
I have captured the event for backspace, but how can I prevent the users from removing the paragraph tags?
I got 11 options (I'm assuming you are using jQuery).
First, capture the keydown event, and if the value is equal to the default value, prevent the action. This will probably be inside to source html of the iframe.
$('#editor').unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8 && $('#editor').html() === '<p><br></p>'){
event.preventDefault();
}
});
Option two: just make the element that's editable a div instead.
I prefer to avoid the use of an iframe. They make things needlessly complicated (imo).
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<script type="text/javascript">
function DoEdit(){
var idContent = document.getElementById('idContent');
idContent.contentEditable = "true";
//var editor = (idContent.contentWindow || idContent.contentDocument).content.document;
//editor.designMode = "on";
//editor.body.contentEditable = "true";
//editor.contentEditable = "true";
}
function ShowContent(){
var contentValue = "<p><br></p>"+$('#idContent').html();
alert(contentValue)
}
$(document).ready(function(){
DoEdit();
$('#showContentBtn').click(function(){
ShowContent();
});
});
</script>
</head>
<body>
<p><br></p>
<div style="text-align: center;margin:0 auto;width: 500px; height: 300px; border: solid; border-width: 2px;">
<div id="idContent" style="text-align: left; width:100%; height: 100%">
</div>
</div>
<div style="text-align: center;"><input id="showContentBtn" type="button" value="Show Content"></div>
</body>
</html>
Added a button in case there was some requirement to get the value for the content and keep those elements in it.
Option 3: If it needs to be inside the iframe, just set url for the above as the src for the iframe.
<html>
<body>
<div style="text-align: center">Edit Frame</div>
<iframe src="/widgets/editor/rich-text" ></iframe>
</body>
</html>
I hope that this will give you a few ideas you can work with inside your project.

How can I make a textarea with character limit highlighting like Twitter?

Twitter's submit tweet textbox highlights the characters that are over the character limit:
As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?
You'll find the necessary solution and required code here:
How to insert <em> tag when exceeding 140 limit i.e. going negative?
...and here:
REGEX - Highlight part over 19 chars
Your question appears to be duplicitous.
Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).
Here's the code as per Simon Kuang's recommendation (see comments):
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h3>Your text here</h3>
<div contenteditable="true" id="myDiv">edit me
</div>
<p>
<h3>Stuff over 19 characters</h3>
<div id="extra">
</div>
<p>
<h3>Sample output</h3>
<div id="sample">
</div>
</body>
</html>
CSS:
.highlight {
color:red;
}
JavaScript:
$(document).ready(function() {
$('#myDiv').keyup(function() {
var content = $('#myDiv').html();
var extra = content.match(/.{19}(.*)/)[1];
$('#extra').html(extra);
var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
$('#sample').html(newContent);
});
});
Here is the example, show alert when the limit is reached and thereafter highlight all the characters entered.
$(document).ready(function() {
var input = $('#text_text');
var warning = $('#warning');
var char_limit = 30;
input.on('keyup', function() {
var val = $(this).val();
if (val.length > parseInt(char_limit)) {
alert("limit reached");
warning.html('hello').css('display', 'block');
l = val.length
var input = document.getElementById("text_text");
input.setSelectionRange(char_limit, l);
input.focus();
} else {
warning.css('display', 'none');
}
});
});
#warning {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test_box">
<textarea name="msg" cols="50" rows="5" id="text_text"></textarea>
<div id="warning"></div>
</div>
Try this (pattern)
html
<data></data><br />
<textarea maxlength="20" placeholder="20 character limit"></textarea>
js
$(function () {
$(document).on("keyup", "textarea", function (e) {
if ($(e.target).val().length >= 20) {
$("data").text($(e.target).attr("placeholder"))
.fadeIn(1000).fadeOut(9000);
};
});
});
jsfiddle http://jsfiddle.net/guest271314/8RScd/

Categories

Resources