JavaScript textarea get numbers of lines (with linebreaks) - javascript

I have a textarea and I want to know how many lines there are. Now I have searched but I only see this solution:
mytextarea.value.split("\n").length
Well, that works but that's not what I want.
For example my textarea is like this:
When I type this:
123456789abcdefghijkl
sasasasakasasask;as
When I use split("\n").value I get 2 which is correct but if I put this in:
123456789abcdefghijklsasasasasasasasasas
I get the result 1 which isn't correct:
The result should be 2 because there are 2 lines however the line breaks are not created with \n.
Anyone an idea how you can calculate the number of lines INCLUDING the line breaks without \n?

The end of each line, hit Enter . when you hit Enter ,insert \n to line.
<html>
<head>
</head>
<body>
<textarea id="myTxt"></textarea>
<button id ="btn" onclick="myLine()">Try</button>
<p id="x"></p>
<script>
function myLine() {
var txt = document.getElementById("myTxt");
var x = document.getElementById("x");
x.innerHTML =txt.value.split("\n").length;
}
</script>
</body>
</html>

Got it!
static lineCaculator() {
let dummy = document.createElement('div');
dummy.style.font = AutoTextareaResizer.computedStyle.call(this, 'font');
dummy.style.width = AutoTextareaResizer.computedStyle.call(this, 'width');
dummy.style.wordWrap = 'break-word';
dummy.innerHTML = this.value;
document.body.appendChild(dummy);
let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) / this.realLineHeight;
document.body.removeChild(dummy);
return Math.max(1, lines);
}

Related

Function output of JavaScript function not showing in html

The Javascript code is working but I don't know how I can make it work in HTML. I want to link it to an external Javascript file.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
console.log(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
HTML code:
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
I believe you want to print or display the output of that function on the web page.
If that's the case. There are various ways to accomplish this.
Before I go any further, I'd want to point out that you are, in fact, printing something, which is what you intended for your function.
But you can't see it since it's printed in the console.
You may view this by using the F12 key after loading your website.
The console will then appear, and the needed output will be printed.
And here's one method for displaying your output in an HTML page.
You just have to replace your console.log() with the document.write().
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
document.write(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
Here is another method to achieve this.
You can add an html element and change the content of that particular element by using document.getElementById("id name of the element").innerHTML.
Here is the code snippet.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
const largest_word = find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']);
document.getElementById("demo").innerHTML =largest_word
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="findLongestWord.js"></script>
</body>
</html>

Make the amount of first and last characters displayed to be responsive to the width available

Maybe someone know how to make text or numbers inside a table cell dynamically change. And if the number or text does not fit into the cell, it was cut off in the middle with an ellipsis, and the letters or numbers that extreme from it hidden or appeared entirely when resizing?
OA210815LXRR1I OA210...LXRR1I OA2...RR1I
I'd like to create something like this: js fiddle
but I don't know how to fix the letter clipping problem when you resize
Try to do this :
var MaxLen = 10;
var limiLen = 5;
var text = document.getElementById("text-test");
if (text.innerHTML.trim().length > MaxLen) {
var newTest =
text.innerHTML.trim().substr(0, limiLen) +
"..." +
text.innerHTML
.trim()
.substr(text.innerHTML.trim().length - limiLen, limiLen);
text.innerHTML = newTest;
}
<html>
<head>
<title> Response </title>
<meta charset="UTF-8" />
</head>
<body>
<div>
<p id="text-test"> ABCDEFGHIJKLMNOPQRSTUVWXYZ </p>
<div>
<script src="index.js">
</script>
</body>
</html>

HTML 5 Validation Error

StackOverflow,
I'm a NOOB learning slowly. I got some errors when trying to validate the following code in HTML 5 validator and don't know where the errors are:
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
<function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</head>
<body>
</body>
</html>
Errors: Error: Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.
From line 5, column 2; to line 5, column 34
↩ ↩
Error: End of file seen when expecting text or an end tag.
At line 18, column 7
dy>↩
Error: Unclosed element script.
From line 5, column 2; to line 5, column 34
↩ ↩
Any feedback? Thanks guys and gals.
PreYvin
You are using typographical quotes - change these to regular quotes. (single and double)
Ok, you've got a whole lot of invalid code (HTML and JavaScript) here:
<!DoctypeHTML>
Should be (case doesn't matter):
<!DOCTYPE html>
This:
<script type = “text/javascript”>
contains typographically formatted quotes instead of non-formatted quotes, which is a problem, but you don't even need the type=text/javascript anyway, so you can just write:
<script>
function is not an HTML tag, so this:
<function substitute () {
should be:
function substitute() {
Next, you are using formatted quotes in your JavaScript:
var MyValue = document.getElementID (‘mytextbox’).value;
which should be unformatted, like this:
var MyValue = document.getElementID ('mytextbox').value;
HTML isn't case-sensitive, but JavaScript is, so this:
If (myValue ==0) {
needs to be this:
if (myValue == 0)
More quote problems here:
alert(‘please enter a real value in the box’);
Should be:
alert('please enter a real value in the box');
More case-sensitivity issues here:
Return;
Should be:
return;
More quote and case-sensitivity issues here:
Var myTitle = document.getElementbyID (‘title’)
Should be:
var myTitle = document.getElementbyID ('title');
Lastly, when your script is finished and it's time to return to HTML, you didn't close your script, so this:
}
</head>
Should be:
}
</script>
</head>
You can always validate your HTML at: http://validator.w3.org
And, you can validate your JavaScript at: http://www.jslint.com
You also have invalid JavaScript so this should be valid.
<!doctype html>
<HTML>
<head>
<title> Javascript Programming!</title>
<script>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
if (myValue ==0) {
alert(‘please enter a real value in the box’);
return;
}
var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
you have an extra < in your code. but you need to revisit your javascript as it has many problems the script tag is not closed.
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
Lots of basic syntax errors here.
<!DoctypeHTML> should be <!DOCTYPE html>
the first error you listed, (Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.) is due to a funky double quote character: “ It should be " This probably originated from your text editor. What are you using? I like Sublime, but there are lots of options. The important thing is that you use a text editor designed for coding.
the next two errors are due to your script tag not being closed. Just add </script> at the end of the script.
Like I said, these are just simple syntax errors though. What you really need to learn here is how to look at those error messages and tell what's going on. Notice how the error messages reference a line number and column number? That's to tell you where the problem is. (Sometimes it can be off depending on the error, but worry about that later). Take a look at the line it's complaining about, read the error message, and you should be able to figure out what's wrong.
Close your <script> tag.
Remove < from <function
Use regular quotes instead of typographical
space between Doctype and html ie. <!doctype html>
Lastly, keywords should be all smallcase ie. if, return, var
Updated
<!doctype html>
<html>
<head>
<title> Javascript Programming!</title>
<script type = 'text/javascript'>
function substitute () {
var MyValue = document.getElementID ('mytextbox').value;
if (myValue == 0) {
alert('please enter a real value in the box');
return;
}
var myTitle = document.getElementbyID ('title')
myTitle.innerHTML = myValue;
}
</script>
</head>
<body></body>
</html>

javascript runtime error 0x800a1391

I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>

deleting random words from html page

I created a javascript program that prints element from my array one by one when you click on the title "click here" , my problem here is that tried to implement a function that deletes a random word from the html page when you click on the words printed previously but it printing other words instead, how can i create a function that removes words printed previously ?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script >
var k = 0;
var ph = ["red ","blue","black","green","yellow"];
function text(){
if(k < ph.length ){
document.getElementById("test").innerText+=" "+ ph[k];
k++;
}
}
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
</script>
</head>
<body>
<h1 onclick="text();">Click here</h1>
<span id="test" onclick="deleteWord();"></span>
</body>
</html>
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
Your problem is that the += operator appends " "+ ph[number] after the current value of the string.
To replace instead, use the = operator to assign a new value. since you want to delete, just use an empty string.
document.getElementById("test").innerText = "";
As a side note it is unusual to store multiple spaces in your string. If you are trying to move the contents around, you should probably consider setting the padding-left CSS property instead.
edit: if you don't want to lose the entire contents of the element, you can replace the last part of the string:
document.getElementById("test").innerText.replace(/ .*$/,"");

Categories

Resources