How to insert html and javascript code with textarea - javascript

I want to insert html and JavaScript code with textarea field in my database. Problem is code has inserted but its replaced all double question with backlash. How to insert this code with textarea.
<div id="TA_cdsratingsonlynarrow539" class="TA_cdsratingsonlynarrow"><ul id="Ny62NY" class="TA_links r04zlbt"><li id="jb9xdEapRG" class="sc9nmfeVX"><a target="_blank" href="https://www.tripadvisor.com/"><img src="https://www.tripadvisor.com/img/cdsi/img2/branding/tripadvisor_logo_transp_340x80-18034-2.png" alt="TripAdvisor"/></a></li></ul></div><script src="https://www.jscache.com/wejs?wtype=cdsratingsonlynarrow&uniq=539&locationId=671932&lang=en_US&border=false&shadow=false&display_version=2"></script>

It is possible to insert/inject html and javascript code using textarea input field into the current page.
consider, you've following textarea:
<div id="output"></div>
<div style="margin: 25px auto; width: 80%; height: auto;">
<form id="myform" name="myform">
<textarea id="mytextarea" name="mytextarea" cols="90" rows="20"></textarea>
<br> <button type="button" id="mybutton">execute</button>
</form>
</div>
Now, you can add event listener to that above button to extract html and javascript code from the textarea and insert them to the page:
window.addEventListener('load', function () {
document.getElementById('mybutton').addEventListener('click', function (e) {
var mytextarea = document.getElementById('mytextarea');
var pattern = /<script>([^]+?)<\/script>/mg;
var matches, txt = mytextarea.value;
if (txt) {
while (matches = pattern.exec(txt)) {
if (matches[1]) {
var tContent = matches[1].replace(/(\n|\r)+/gm, '');
var s = document.createElement('script');
s.innerText = tContent;
document.body.appendChild(s);
}
}
txt = txt.replace(pattern, '');
}
if (txt) {
document.getElementById('output').innerHTML = txt;
}
});
});

Related

Reusable function to display input text in div

I have a function that displays text in a div as its typed into an input. Right now it simply checks for each ID go get the value and display the text.
I want to make this function reusable so that I can match different inputs with different divs without writing a unique function for each case.
Here is an example that works using a single input and div:
<body>
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<script type="text/javascript">
var displayText = document.getElementById('inputBox');
displayText.onkeyup = function() {
document.getElementById('displayBox').innerHTML = inputBox.value;
}
</script>
</body>
And I want to be able to repeat this for different sets of unique inputs & divs with a reusable function.
<body>
<!-- First set -->
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<!-- Second set -->
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<!-- etc... -->
<script type="text/javascript">
var displayText = document.getElementById('inputBox');
displayText.onkeyup = function() {
document.getElementById('displayBox').innerHTML = inputBox.value;
}
</script>
</body>
If you wrap each "set" in a container, and swap your ids for classes, you can can add listeners to each input to watch for changes, find the parent container, find the display box and update its text content.
// Get all of the inputs
const displayText = document.querySelectorAll('.inputBox');
// Attach listeners to all of them
displayText.forEach(input => {
input.addEventListener('keyup', handleChange, false);
});
function handleChange() {
// Find the closest div ancestor element (the container)
const parent = this.closest('div');
// Then locate the display box and update the text content
parent.querySelector('.displaybox').textContent = this.value;
}
.container { margin-bottom: 1em; }
.displaybox { margin-top: 0.2em; height: 1.3em; width: 300px; border: 1px solid black; }
<div class="container">
<input type="text" name="name" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
<div class="container">
<input type="text" name="age" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
<div class="container">
<input type="text" name="location" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
It seems you would need to get the ID of each input box and each output box?
function showTypedInput(inputID, outputID) {
var inputBox = document.getElementById(inputID);
var outputBox = document.getElementById(outputID);
inputBox.onkeyup = function(){
outputBox.innerHTML = inputBox.value;
};
}
Then you just reuse this?
showTypedInput("myInputBox", "myOutputBox");
You can create this functionality using following:
function listener(target){
return function(e){target.innerHTML = e.target.value};
}
function init(){
var elems = document.querySelectorAll("input[data-keyuptarget]");
for(var elem of elems){
var target = document.getElementById(elem.getAttribute('data-keyuptarget'));
if (target) elem.onkeyup = listener(target);
}
}
init();
In html just use
<input type='text' name='name' data-keyuptarget="displayBox1">
<div id='displayBox1'></div>
<input type='text' name='name' data-keyuptarget="displayBox2">
<div id='displayBox2'></div>
JS Bin : https://jsbin.com/piwiyapohe/edit?html,output

Adding labels to QR codes

I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them

How to count number of words in a textfield

I have a user enter biograpgy in a text box html for that is
<p>Biography:
<input type="text" id="biography" name="biography" />
<span id="biographyInvalid" style="color:red; visibility:hidden"> Biography is Invalid </span>
</p>
for Javascript i have a checkme function that is called and i want to do a check inside of it
function checkme(){
var biography=document.getElementById('biography').value;
}
how can i count number of words, do i first convert it to string and then separate with spaces
<div>
<div id="count">145</div>
<div id="barbox"><div id="bar"></div></div>
</div>
<textarea id="contentbox"></textarea>
and js
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var box=$(this).val();
var main = box.length *100;
var value= (main / 145);
var count= 145 - box.length;
if(box.length <= 145)
{
$('#count').html(count);
$('#bar').animate(
{
"width": value+'%',
}, 1);
}
else
{
alert(' Full ');
}
return false;
});
});
</script>
$('#contentbox').keyup(function(){} - contentbox is the ID of the textbox.
Using $(this).val() getting the textbox value.
bar is the div ID of the count meter $('#bar').animate() increasing the width.
js:
$('#biography').keyup(function () {
var words = this.value.match(/\S+/g).length;
$('#count').html('Words Count:'+words);
});
HTML:
<div id="count"></div>
This gives you correct words count
This is working example
the HTML
<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4" onkeyup="countNoOfWords()" >This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input name="noofwords" type="text" value="" size="6" />
</form>
The JS function
<script type="text/javascript">
function countNoOfWords(){
document.myform.noofwords.value = document.myform.post_content.value.split(' ').length;
}
</script>
reference
$('input').keyup(function() {
var cs = this.value.match(/\S+/g).length;
$('#biography').text(cs);
});
Demo - http://jsfiddle.net/hNn5b/685/

Cannot convert dynamically loaded teaxtarea into ckeditor

calling this get_content function after clicking a link.
function get_content(n)
{
var hr=new XMLHttpRequest();
var url="./updatecontent.php";
var vars="id="+n;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange=function()
{
if(hr.readyState==4 && hr.status==200)
{
var return_data=hr.responseText;
document.getElementById("content").innerHTML=return_data;
}
}
hr.send(vars);
document.getElementById("content").innerHTML='<img src="./img/loading.gif">';
}
<div id="content"></div>
The following is the response data
<div id="text-editor" style="width:100%;">
<form action="" method="post">
<textarea class="ckeditor" name="editor1" id="txt1"></textarea>
<input type="submit" name="update" value="Update">
</form>
</div>
<script src="./ckeditor/ckeditor.js"></script>
The response data is succefully added to div id="content"
The relative link to ckeditor is correct.But the textarea is not converting into CKeditor.
where is the mistake? please help.
In this case you need to call CKEDITOR.replace('editor1') after content being changed.
So in your case it will be
function get_content(n)
{
var hr=new XMLHttpRequest();
var url="./updatecontent.php";
var vars="id="+n;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange=function()
{
if(hr.readyState==4 && hr.status==200)
{
var return_data=hr.responseText;
document.getElementById("content").innerHTML=return_data;
CKEDITOR.replace('editor1'); // <-- add this line
}
}
hr.send(vars);
document.getElementById("content").innerHTML='<img src="./img/loading.gif">';
}

add 10 text boxes one by one on clicking add more button

In my form i am having a button to Add More EmailId where i have to give ten textbox one by one can anybody please tell about appropriate javascript..
Try something like this, its something I ripped from another project.
Wrap your form around the div and when you submit your email addresses will be in an array as the name of the input box is email[].
<div class="cntdelegate">
<div id="readroot" style="display:none;">
<table cellspacing="0">
<tr>
<td><label for="theiremail"><span>Email</span></label><input type="text" name="email[]" id="theiremail" value="Email" class="emailbox" maxlength="100" onFocus="if(this.value=='Email'){this.select()};" onClick="if(this.value=='Email'){this.select()};" /></td>
</tr>
</table>
Remove
<div class="clear"></div>
</div>
<span id="writeroot"></span>
<button style="float:right!important;" type="submit" class="withArrow" name="submit" id="submit" value="submit" alt="Send" title="Send">Book now</button>
<div class="addDelegate" style="float:left!important;">
Add another delegate
</div>
<div class="clear"></div>
</form>
</div>
<script>
var counter = 0;
function init() {
moreFields();
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = function ()
{
if (self.init)
init();
}
</script>
I'm unsure what html you have but I've created a simple jQuery example here http://jsfiddle.net/TsmTg/2/
Here's the code
$(function(){
var emailAddress = $("[name=emailAddress]");
$("#addEmailAddress").click(function(){
emailAddress.after(emailAddress.clone());
});
});​
This will copy your email input and just add a clone after the original. All the email address inputs will have the same name so you will have to handle parsing the data on the server side. You could modify it so each email address input has a different name by using a counter to append a number to the end of each input, like so:
$(function(){
var emailAddress = $("[name=emailAddress]");
$("#addEmailAddress").click(function(){
var newEmail = emailAddress.clone();
newEmail.attr("name", newEmail.attr("name") + ($("[name^=emailAddress]").length + 1));
emailAddress.after(newEmail);
});
});
Are you using Tables to put the textboxes? In that case, cloning rows from the table easily adds a new row with the contents in a table.
Add your HTML code. This will help finding the solution easier.

Categories