JavaScript to paste form input in-line into body text - javascript

I have an HTML form with input text fields which i would like to have pasted back into the HTML body resulting in a text string returned by a JavaScript function i.e. in the place where the input fields are sequentially. A simple example would be:
<html>
<body>
This is the first field <input type="text" id="first"/>
and this is the second <input type="text" id="second"/> one.
</body>
</html>
When i now view this page and enter ABC into field 1 and XYZ into field 2, i'd like to know how to use JavaScript to create a piece of text like so:
This is the first field ABC and this is the second XYZ one.
So just to be clear, the web page itself need not change dynamically, i only want to be able to call the JavaScript function from elsewhere and then get the resulting text back with whatever is currently entered, pasted into the body text.
Any help much obliged.
Tiaan

You can use the DOM to loop through the child nodes of body (probably recursively), collecting the nodeValue properties of the text nodes (those are the bits containing "This is the first field " and such) and, where you encounter an input element, getting its value property instead. Build all of that text up into a string and you're there.
Some references:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs

Place form text and input fields into a div and call makeRecursive() (i.e. no args) to kick-start the text creation.
function makeRecursive(o)
{
var b = o || document.getElementsByTagName('div')[0];
var t = "";
if (b.nodeType === 1 && b.tagName === "INPUT")
t += b.value;
else if (b.nodeType === 3)
t += b.nodeValue;
if (b.hasChildNodes())
{
var c = b.firstChild;
while (c)
{
t += makeRecursive(c);
c = c.nextSibling;
}
}
return t;
}

Related

Passing newline character as variable to insertText in GAS

I am using an apps script Sidebar to insert text, where I enter need to append some text at the beginning, then after typing again append.
The appended text will be determined by the text box in the sidebar.
I pass the values as formObject
function sendform(){
var f = document.forms[0].elements;
var data = { "mytext": f[0].value }
google.script.run.withSuccessHandler(ready).withFailureHandler(onFailure).processForm(data);
}
Here is the apps script code.
function processForm(fO)
{
var body = DocumentApp.getActiveDocument().getBody();
body.editAsText().insertText(0, "\n\nsometext");
// this will perfectly insert the newlinenewlinesometext to the document
body.editAsText().insertText(0, fO.mytext);
// this will insert \n\nsometext which is wrong
}
I tried using encodeURIComponent decodeURIComponent, but still its the same problem.
Any suggestions?
You may want to first check the rules given in Structure of a document wherein you will find tree showing which text elements can be inserted and which elements can only be manipulated in place.
As mentioned, the Document Service in Apps Script can only insert certain types of elements. If you find in tree that you're trying to insert an allowable element, see Class Text to know the methods you can use on how to insert text such as insertText(offset, text).
Here's the sample code in inserting text:
var body = DocumentApp.getActiveDocument().getBody();
// Use editAsText to obtain a single text element containing
// all the characters in the document.
var text = body.editAsText();
// Insert text at the beginning of the document.
text.insertText(0, 'Inserted text.\n');
// Insert text at the end of the document.
text.appendText('\nAppended text.');
// Make the first half of the document blue.
text.setForegroundColor(0, text.getText().length / 2, '#00FFFF');

How do I get user input from input area with Java Script and assign to a variable?

I'm trying to make a simple mad libs type game. To do so I need to do the following:
Have space that user can input text
Retrieve text that user inputted
Assign text to variables using Javascript
Place variables in Mad libs
I know how to do this using something like:
var userAnswer = prompt("Give me an answer");
However, I want to get the input from a text input field. I was trying to do the following but I got stuck:
Have input area with id="input1"
Create function that takes content of #input1 and assign to a variable.
Use button to run the function
I will then later use these variables in my story
<label for='input1'>Verb + ing</label><input id='input1'>
<script>
var setInputs = function() {
var space1 = document.getElementById("input1").innerHTML;
}
</script>
<button onclick="setInputs">Click me</button>
I'm I going about this the correct way?
Fiddle: http://jsfiddle.net/6rjf5k9n/
Try This
<label for='input1'>Verb + ing</label><input id='input1'>
<script>
var setInputs = function() {
var space1 = document.getElementById("input1").value;
alert(space1);
}
</script>
<button onclick="setInputs()">Click me</button>
.value gives you the currently-set value of a form element (input, select, textarea), whereas
.innerHTML builds an HTML string based on the DOM nodes the element contains.

Can jQuery or Javascript change elements within textareas?

My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/

javascript/jquery- how to check, if an element has text attribute or not

Is there some way of determining at run time, if an element returns value for element.text() or not? Using javascript or jquery?
I.E. some way of checking if an element is pure text, or it is some other type of element?
Why I need a solution to the above---
I am trying to parse through some complicated forms with totally different coding styles (in the way, for example, text values for elements of a radio button may be enclosed in label tags, or they may be directly given, or they may be enclosed in span tags, and so on...)
So I need to parse the form with the form id as wrapper,
now if the text value for a radio button is enclosed in span, and current selected element is radio button, then next element will be the span tag (opening) which I want to do nothing with and move on. The one after that will be the text, and this I want to obtain using this.text().
Hence the whole question...
You can use nodeType to check if an element is pure text (in which case its value will be 3)
<div id="wrapper"><input type='radio' />some text here</div>
$('#wrapper').contents().each(function()
{
alert(this.nodeType);
});
It will alert 1 (for input) and 3 (for text). For type=3, you can use text() to get text value
Note- It'll also taken into account white spaces (as text nodes).
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== 'undefined' && attr !== false) {
// ...
}
Another way to check:
if( typeof( $(this).attr('name') ) != 'undefined' ) { // ... }
you can create you own extension method of jQuery:
$.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};
$(document).ready(function() {
if($('.edit').hasAttr('id')) {
alert('true');
} else {
alert('false');
}
});
<div class="edit" id="div_1">Test field</div>
hi you can check the type of element as follow
<form >
<input type="text" id="a" value="abc"/>
</form>
<script>
var type = document.forms[0].elements[0].type;
alert(type);
</script>

How to prevent script tags in text from executing?

I had a text box in my browser. Whatever you typed in the text box and clicked on okay button, the text submitted server through a AJAX request and then spread that message to remaining people, including to me also.
The message is appeared on a <div>.
What's my problem is if I typed html or script tags in that message they are not appearing in the message <div> and they are executing .
If I typed like tags opened and end with script in that middle code is executing on client side, how can I prevent executing and I am able to spread <script> tags also in the messages spreading to all.
If you want the text to always be text, treat is as text and don't use it to set innerHTML property for example.
Update text nodes instead.
Update
For example, if you had user input in userInput, and you wanted to display it, you would treat it as text, not HTML.
var element = document.body,
// For example
userInput = "Alex <script>alert('xss')</script>";
// Don't do this! Your input is text, not HTML.
// element.innerHTML = userInput;
// Use this instead
if ('textContent' in element) {
element.textContent = userInput;
} else {
element.innerText = userInput;
}
jsFiddle.
Have you tried replacing with html character entities? For example replacing all < with <.

Categories

Resources