I need to add line break when the text overflows
ex. if the text is
wwwwwwwwwwwwwww
wwwwwwwwwwwwwww
which is with in the textarea
the data should be with the line break.
Currently the data it is displaying is
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww.
I need to show the exact way how the data is entered in textarea.
When the text overflows it moves to next line in the textarea,but when the data is retrieved the line break is not retained. It just displays as a single line
Or is there any way we can know that overflow occurs so that new line can be added?
I got the answer from the below fiddle which applies the line break to each next line
http://jsfiddle.net/pH79a/218/
html
<div>
<textarea rows="5" id="myTextarea" ></textarea>
</div>
<div id="pnlPreview"></div>
<div>
<button type="button" onclick="ApplyLineBreaks('myTextarea');">Apply Line Breaks</button>
</div>
javascript
function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
oTextarea.setAttribute("wrap", "off");
}
else {
oTextarea.setAttribute("wrap", "off");
var newArea = oTextarea.cloneNode(true);
newArea.value = oTextarea.value;
oTextarea.parentNode.replaceChild(newArea, oTextarea);
oTextarea = newArea;
}
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
function testBreak(strTest) {
oTextarea.value = strTest;
return oTextarea.scrollWidth > nEmptyWidth;
}
function findNextBreakLength(strSource, nLeft, nRight) {
var nCurrent;
if(typeof(nLeft) == 'undefined') {
nLeft = 0;
nRight = -1;
nCurrent = 64;
}
else {
if (nRight == -1)
nCurrent = nLeft * 2;
else if (nRight - nLeft <= 1)
return Math.max(2, nRight);
else
nCurrent = nLeft + (nRight - nLeft) / 2;
}
var strTest = strSource.substr(0, nCurrent);
var bLonger = testBreak(strTest);
if(bLonger)
nRight = nCurrent;
else
{
if(nCurrent >= strSource.length)
return null;
nLeft = nCurrent;
}
return findNextBreakLength(strSource, nLeft, nRight);
}
var i = 0, j;
var strNewValue = "";
while (i < strRawValue.length) {
var breakOffset = findNextBreakLength(strRawValue.substr(i));
if (breakOffset === null) {
strNewValue += strRawValue.substr(i);
break;
}
nLastWrappingIndex = -1;
var nLineLength = breakOffset - 1;
for (j = nLineLength - 1; j >= 0; j--) {
var curChar = strRawValue.charAt(i + j);
if (curChar == ' ' || curChar == '-' || curChar == '+') {
nLineLength = j + 1;
break;
}
}
strNewValue += strRawValue.substr(i, nLineLength) + "\n";
i += nLineLength;
}
oTextarea.value = strNewValue;
oTextarea.setAttribute("wrap", "");
document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(new RegExp("\\n", "g"), "<br />");
}
word-wrap: break-word is your friend. Try this code.
textarea {
word-wrap: break-word;
}
Try cols attribute of the textarea
<textarea rows="4" cols="40">
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
</textarea>
Do this
<input type="text" style="overflow-wrap: break-word;">
In PHP u usually use nl2br() function.
Please refer to the below question, I am sure that it will help you!
jQuery convert line breaks to br (nl2br equivalent)
Use word-wrap for textarea reference to below link: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_word-wrap
This simple line of code can help you with the task:
<textarea id="textbox" rows="10" cols="30"></textarea>
But you should search it on web and there are many questions with the same context on the stackoverflow itself.
You can try it here but I think it is not needed:
https://jsfiddle.net/thisisdg/8f3y5r4d/
I hope this helps.
Related
I have coded the below piece of code which handle the number bigger than 999 and add a comma to it. For example 1,000 and 1,000,000. Wheare as once the number increase the comma will be placed in the correct position. I used DRY principle and I feel still there is another easy way to handle it.
Now, I want to know if there is much better way than that I did.
Waiting for your opinion.
Thanks.
function seperate_num_by_comma() {
var num = '199228754645.25',
withOutComma = num.split('.'),
addNewCommaAfter = 3,
x = withOutComma[0].length % addNewCommaAfter,
lenOfWithOutComma_0 = withOutComma[0].length,
length_1 = withOutComma[0].length - x,
starter = 0,
wholeNumber = ' ';
for (var i = 0; i < lenOfWithOutComma_0; i++) {
function run_first_func() {
wholeNumber += withOutComma[0].substr(starter, addNewCommaAfter);
};
function run_second_fun() {
wholeNumber += withOutComma[0].substr(starter, addNewCommaAfter) + ",";
starter += addNewCommaAfter;
length_1 -= addNewCommaAfter;
};
if (x > 0) {
if (length_1 == 0) {
run_first_func();
break;
} else if (wholeNumber == ' ') {
wholeNumber += withOutComma[0].substr(starter, x) + ",";
length_1 -= addNewCommaAfter;
starter = x;
} else {
run_second_fun();
}
} else if (x == 0) {
if (length_1 == 3) {
run_first_func();
break;
}
run_second_fun();
}
}
console.log(wholeNumber + '.' + withOutComma[1]);
}
seperate_num_by_comma();
One Line:
165B minified version (no IE): seperate_by_comma=t=>(x=(""+t).split("."),z=x[0].replace(/((\d{3})*?)(\.|$)/,"|$1").split("|"),x[0]=z[0]+z[1].replace(/(.{3})/g,",$1").slice(!z[0].length),x.join("."))
OR 180B, IE-friendly: seperate_by_comma=function(t){x=(""+t).split(".");z=x[0].replace(/((\d{3})*?)(\.|$)/,"|$1").split("|");x[0]=z[0]+z[1].replace(/(.{3})/g,",$1").slice(!z[0].length);return x.join(".")}
Explanation:
seperate_num_by_comma = function(number){//12345678.9
var str = String(t);
var withoutDot = str.split("."); //["12345678", "9"]
var chunksOfThree = withoutDot[0].replace(/((\d{3})*?)(\.|$)/,"|$1");//"12|345678"
chunksOfThree = chunksOfThree.split("|");//["12", "345678"]
chunksOfThree[1] = chunksOfThree[1].replace(/(.{3})/g,",$1") //",345,678"
if(chunksOfThree[0].length==0){
chunksOfThree[1] = chunksOfThree[1].slice(1); //Fix for specific cases
}
withoutDot[0] = chunksOfThree[0] /*"12"*/ + chunksOfThree[1] /*",345,678"*/
return withoutDot.join(".") //"12,345,678.9"
}
Hello I don't know if my title is helpful at all but here is my problem I want to make a type writer effect in JS, CSS, HTML, everything works fine apart from add a new line of text when I try added a new line it dose not show.
var str = "<p>I want to put text here then another line under this one</p>",
<!--var str = "<p>text here</p>",--> <!--This is what I tried to do to add a new line-->
i = 0,
isTag,
text;
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('typewriter').innerHTML = text;
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 80);
}());
#typewriter {
color: lime;
text-align: center;
}
<div id="typewriter"></div>
var str = "My text\nSome more text";
var stra = str.split("");
var tw = document.getElementById("output");
function type(){
var char = stra.shift();
if (char){
tw.innerHTML += char;
setTimeout(type, 80);
}
}
type();
<pre id="output"></pre>
use <br />
var str = "<p>I want to put text here<br /> then another line under this one</p>";
Another possibility is to group paragragh elements using span and add display style property of span to block.
window.onload = function () {
var str = "<p><span>I want to put text here then another line under this one</span><span>text here</span></p>";
(function type(isInTagArg, indexArg) {
var index = indexArg || 0;
if (index >= str.length)
return;
var isInTag = isInTagArg || false;
if (isInTag == false) {
if (str.charAt(index) == '<') {
return type(true, index + 1);
} else {
document.getElementById('typewriter').innerHTML = str.substr(0, index + 1);
}
} else {
if (str.charAt(index) == '>') {
return type(false, index + 1);
}
return type(true, index + 1);
}
setTimeout(function() {type(false, index + 1)}, 80);
}());
}
#typewriter {
color: lime;
text-align: center;
}
#typewriter span
{
display: block;
}
<div id="typewriter"></div>
i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>
I'm having a text area, user can type in the text area, in start it will be lower case, but once user click on the 'T(toggle)' button, what ever typing after that will change to upper case previous one will be in lower case only . If again user click on the 'T(toggle button)' what ever type after that will appear in lower case and so on. I tried but that was not successful.
<input type="button" name="toggleCase" id="toggleCase" value="T" style="width:40px;" onclick="javascript:changeCase(this);" />
<textarea tabindex="1" cols="39" rows="2" onkeydown="checkTxtCase(this);" name="titleText1"> </textarea>
JS:
function checkTxtCase(elmObj) {
setCursorToTextEnd(elmObj.id);
var txtVal = elmObj.value;
var txtLen = txtVal.length;
prevSize = txtLen;
var txtLast = txtVal.substring(txtLen - 1, txtLen);
if (textCase == 'LOWER') {
elmObj.value = txtVal.substring(0, txtLen - 1) + txtLast.toLowerCase();
} else {
elmObj.value = txtVal.substring(0, txtLen - 1) + txtLast.toUpperCase();
}
return true;
}
function setCursorToTextEnd(textControlID) {
var text = document.getElementById(textControlID);
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
var textCase = 'UPPER';
var prevSize = 0;
function changeCase() {
document.getElementById('titleText1').focus();
textCase = (textCase == 'LOWER') ? 'UPPER' : 'LOWER';
}
Any suggestion is appreciated.
var textCase = 'toLowerCase';
var pos = 0;
function changeCase() {
var textarea = document.getElementsByName('titleText1')[0];
pos = textarea.value.length;
textCase = (textCase == 'toUpperCase') ? 'toLowerCase' : 'toUpperCase';
textarea.focus();
}
function checkTxtCase(elem) {
var l = elem.value.substr(pos);
elem.value = elem.value.substr(0, pos) + l[textCase]();
}
FIDDLE
I have found out a plugin for you. Its really cool and it really works.
http://jquerybyexample.blogspot.com/2011/12/jquery-plugin-for-uppercase-lowercase.html
This will help you
I have created a fiddle for you. Check It
http://jsfiddle.net/KKX5G/2/
$('#Txt').Setcase({caseValue : 'lower'});
I have a textbox which I want to set the focus on, but it doesn't work.
document.getElementById("txtCity").focus();
Any idea?
Maybe you are calling the JavaScript before the input element is rendered? Position the input element before the JavaScript or wait until the page is loaded before you trigger your JavaScript.
In that order, it works just fine:
<input type="text" id="test" />
<script type="text/javascript">
document.getElementById("test").focus();
</script>
In jQuery you could place your code within the .ready() method to execute your code first when the DOM is fully loaded:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#test").focus();
// document.getElementById("test").focus();
});
</script>
In case someone searching has a similar situation to mine ... I had to set a tabindex attribute before my div could receive focus():
featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true
(I found my answer here: Make div element receive focus )
And of course, make sure the body element is ready before setting focus to a child element.
I have also faced same problem.To resolve this problem, put your code in setTimeout function.
function showMeOnClick() {
// Set text filed focus after some delay
setTimeout(function() { jQuery('#searchTF').focus() }, 20);
// Do your work.....
}
Try to wrap it into document ready function and be sure, that you have jquery included.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#test").focus();
});
</script>
<div id="txtROSComments" contenteditable="true" onkeyup="SentenceCase(this, event)"style="border: 1px solid black; height: 200px; width: 200px;">
</div>
<script type="text/javascript">
function SentenceCase(inField, e) {
debugger;
var charCode;
if (e && e.which) {
charCode = e.which;
} else if (window.event) {
e = window.event;
charCode = e.keyCode;
}
if (charCode == 190) {
format();
}
}
function format() {
debugger; ;
var result = document.getElementById('txtROSComments').innerHTML.split(".");
var finaltxt = "";
var toformat = result[result.length - 2];
result[0] = result[0].substring(0, 1).toUpperCase() + result[0].slice(1);
if (toformat[0] != " ") {
for (var i = 0; i < result.length - 1; i++) {
finaltxt += result[i] + ".";
}
document.getElementById('txtROSComments').innerHTML = finaltxt;
alert(finaltxt);
abc();
return finaltxt;
}
if (toformat[0].toString() == " ") {
debugger;
var upped = toformat.substring(1, 2).toUpperCase();
var formatted = " " + upped + toformat.slice(2);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
finaltxt += result[i] + ".";
}
}
}
else {
debugger;
var upped = toformat.substring(0, 1).toUpperCase();
var formatted = " " + upped + toformat.slice(1);
for (var i = 0; i < result.length - 1; i++) {
if (i == (result.length - 2)) {
finaltxt += formatted + ".";
}
else {
//if(i
finaltxt += result[i] + ".";
}
}
}
debugger;
document.getElementById('txtROSComments').value = finaltxt;
return finaltxt;
}
</script>
<script type="text/javascript">
function abc() {
document.getElementById("#txtROSComments").focus();
}
It works fine in this example
http://jsfiddle.net/lmcculley/rYfvQ/