html - Get wrapped text from textarea - javascript

I'm trying to get the word wrapped line breaks from a textarea without having make any server calls. This answer gets me 90% of the way there. The problem is that the page is reloaded inside of the iframe each time the submit button is clicked. Here's the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<script type="text/javascript">
function getURLParameter(qs, name) {
var pattern = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(pattern);
var res = regex.exec(qs);
if (res == null)
return "";
else
return res[1];
}
function getHardWrappedText() {
var frm_url = document.getElementById('frame').contentDocument.URL;
var text = unescape(getURLParameter(document.getElementById('frame').contentDocument.URL, 'text')).replace(/\+/g, ' ');
return text;
}
function onIFrameLoad() {
var text = getHardWrappedText();
console.log(text);
}
window.onload = function() {
console.log("loading")
};
</script>
<form name="form" method="get" target="frame">
<textarea id="text" name="text" cols=5 wrap="hard">a b c d e f</textarea>
<input type="submit">
</form>
<iframe id="frame" name="frame" onload="onIFrameLoad()" style="display:none;"></iframe>
</body>
</html>
Clicking on the submit button gives the output:
loading
a b c d e
f
Is there a way to prevent the iframe from reloading the page?

You have to return a false to the onsubmit event of the form.
<form name="form" method="get" target="frame" onsubmit="onIFrameLoad">
If it is based on some condition that you do not want to load
function onIFrameLoad() {
var text = getHardWrappedText();
console.log(text);
if(text.indexOf('\n')<0) return false;
}
Am just putting a random thing at text.indexOf('\n')<0, you can have anything that makes sense or always return false (which looks unlikely)

Related

Censoring / Highlighting using JavaScript

I'm trying to create a small sample application for highlighting / censoring of a textarea using JavaScript. To start with I'm just trying to replace the letters, though once that is solved my plan was to use mark.js to mark censored words. Right now when I run my application I'm getting Uncaught TypeError: Cannot Read property 'value' of null on line 21.
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('comments');
var badWords = ["x", "y", "z"];
var censored = censore(commentContent.value, badWords);
}
function censore(string, filters) {
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea id="pesho" name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('pesho');
var badWords = ["crap", "fuck", "cunt"];
console.log(commentContent.value)
commentContent.value =censore(commentContent.value, badWords);
}
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
As some of the other guys before me mentioned, you were not targeting the id of the text area but the name attribute, beside that for the function to make actual changes on the view you must change the targeted element value (see the modified example)

Javascript check textarea for specific text

I have a text area on a simple website that I would like to check for specific text. The text that I would like to check for are html tags. It works when I put the tags right next to each other. I want to make sure that the text area has the tags but with any number of spaces or breaks. Thanks in advance!
Here is my full code:
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function checkform ( form )
{
// see http://www.thesitewizard.com/archive/validation.shtml
// for an explanation of this script and how to use it on your
// own website
// ** START **
if (form.email.value == "<html><head></head><body></body></html>") {
var node = document.getElementById("grr");
node.innerHTML = "<p>" + "Correct!" + "</p>";
form.email.focus();
return false ;
}
// ** END **
return true ;
}
//-->
</script>
</head>
<body>
<form action="#" method="post" onsubmit="return checkform(this);">
<textarea id="email" type="text" rows="5" columns="5"></textarea>
<input type="submit" value="submit">
</form>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
<div id="grr">Text</div>
</body>
</html>
There's not many good ways to do this. Generally you should parse HTML in the browser and return the HTML string, as that would solve the issue for the most part, but you can't really insert an entire document with <html>, <head> tags and everything into another element, so you're probably left with a regex solution, something like this
function checkform(form) {
var div = document.createElement('div'),
email = document.getElementById('email');
if (email.value.replace(/\>\s+\</g, '><').trim() == "<html><head></head><body></body></html>") {
var node = document.getElementById("grr");
node.innerHTML = "<p>" + "Correct!" + "</p>";
email.focus();
return false;
}
return true;
}
FIDDLE

JavaScript Replace Method for multiple textboxes

Can anyone please tell me how I can use the replace method to replace a character if it occures in more than one textbox without having to write separate function for each textbox.
The code below is the basic way to use the replace method but it only allows for one textbox.
I'm sure I need a loop in there but I'm not sure how to use that without affecting the replace method.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function stringReplace(form) {
var replaceStr = form.textfield1.value
var pattern = /\'/g;
form.textfield1.value = replaceStr.replace(pattern, "''");
}
</script>
</head>
<body>
<form name="form1" method="post" action="JStest_redirect.asp">
<p>fname:
<input type="text" name="textfield1" size="20">
</p>
<p>lname:
<input type="text" name="textfield2" size="20">
</p>
<p>
<input onclick="return stringReplace(form)" type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
You can do this:
function stringReplace(form) {
var $inputs = $(form).find('input:text');
var pattern = /\'/g;
$inputs.each(function () {
this.value = this.value.replace(pattern, "''");
});
return false; // Prevent the form from being submitted
}
This would find all the input type text within the form and replace their values.
If you wish to do it without jquery, you can use the getElementsByTagName() method.
function stringReplace(form) {
var pattern = /\'/g;
var inputs = form.getElementsByTagName("input");
var input;
for (var i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.type = 'text') {
var replaceStr = input.value;
input.value = replaceStr.replace(pattern, "''");
}
}
return false;
}
You seem to want
function stringReplace(form) {
$('input[type=text]').val(function(_, v) {
return v.replace(/\'/g, "''");
});
return false;
}
I added a return false at the end to prevent the form to be submitted on click. You probably want to have a separate button in your case.
I believe that fisrt you have to take all the values
function GetValue(){
var Contain = "";
$("#form1 :text").each(function(){
//add replace code here
});
}
You can add onchange function to all of you text input
function stringReplace(textField) {
var replaceStr = this.value
var pattern = /\'/g;
this.value = replaceStr.replace(pattern, "''");
}
and than you add
<input type="text" name="textfield1" size="20" onchange="stringReplace(this);">

Javascript disabling input fields

I am looking for a javascript function. which will disable the entered (filled) text field on submit. So when the user logs in back the filled text box has to remain disabled. I have tried a code, but here what happens is on clicking the sumbit the contents in the text field gets deleted.
<html>
<head>
<script>
function enableDisable(){
var disable = true;
var arglen = arguments.length;
var startIndex = 0;
var frm = document.example1;//change appropriate form name
if (arglen>0){
if (typeof arguments[0]=="boolean") {
disable=arguments[0];
if (arglen>1) startIndex=1;
}
for (var i=startIndex;i<arglen;i++){
obj = eval("frm."+arguments[i]);
if (typeof obj=="object"){
if (document.layers) {
if (disable){
obj.onfocus=new Function("this.blur()");
if (obj.type=="text") obj.onchange=new Function("this.value=this.defaultValue");
}
else {
obj.onfocus=new Function("return");
if (obj.type=="text") obj.onchange=new Function("return");
}
}
else obj.disabled=disable;
}
}
}
}
</script>
</head>
<body>
<form name="example1">
Text Field: <input type="text" name="text1">
<br>
<input type="submit" name="control1" onclick="enableDisable(this.submit,'text1','submit','select1')">
</form>
</body>
</html>
please do guide.
Make sure your submit function returns false if you don't want the page to refresh. The code you're looking for is document.getElementById('insertIdOfTextFieldHere').style.readonly = "readonly";

JavaScript textbox new line replacement

I have a text box that can allow the users to hit enter. When they hit enter I check the input and replace the carriage return with \n. However it still sends to my database a carriage return.
What could be wrong?
Here is the code:
var pp = comment.value;
alert(pp.replace(/\r?\n|\r/g, "\n"));
comment.value = pp.replace(/\r?\n|\r/g, "\n");
and in my database I still get carriage return character even though I am replacing it.
If you set an onsubmit handler on your form, you'll be able to change the contents of the textarea element before sending it. You can then use the replace method to change every \r to \n:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Replace carriage returns in textarea</title>
</head>
<body>
<form id="theForm">
<textarea id="theTextarea" name="txtarea" rows=10 cols=50></textarea>
<input type="submit" value="Send">
</form>
<script>
function replace_newlines() {
var textField = document.getElementById("theTextarea");
var textString = textField.value;
textField.value = textString.replace(/\r/g, "\n");
}
document.getElementById("theForm").onsubmit = replace_newlines;
</script>
</body>
</html>
Here is an example that does it in pure javascript, but it'd be much cleaner if you were using something like jquery.
<html>
<head>
</head>
<body>
<textarea id='txt'></textarea>
<script type='text/javascript'>
var txtarea = document.getElementById('txt');
txtarea.onkeypress = keyHandler;
function keyHandler(e){
if (document.all) { e = window.event; }
if (document.layers || e.which) { pressedKey = e.which; }
if (document.all) { pressedKey = e.keyCode; }
if(pressedKey == '13'){
txtarea.value = this.value + '\\n';
return false;
}
}
</script>
</body>
</html>

Categories

Resources