Targeting plain text with jQuery - javascript

I'm trying to isolate (and then manipulate) quote block formatted in common newsreader and email-client manner.
The HTML:
<p>
Hello there!
<br />
I'm great, how are you?
<br />
<br />
Someone wrote:
<br />
> Greetings,
<br />
> How are you?
</p>
I need to target all the lines that start with >, and hide them as a collapsable block. In the above example everything bellow "Someone wrote:" would then be hidden, saved as a variable and the end result produced by JS would be:
<p>
Hello there!
<br />
I'm great, how are you?
<br />
<br />
Someone wrote:
<br />
Click to expand
</p>
Gmail does the same thing, but it serverside wraps the quotation block in a <div>, due to the specific nature of my project the complete process has to be done by JS alone.
I'm working with the jQuery framework.
Thanks in advance!

I don't believe jquery parses text like this. You'll have to parse it yourself for lines that start with '>' and edit the string as you'd like. Then you can use jquery to act on the elements you added.

I put together an example for you at this pastebin. Here is the code with comments added.
HTML
<p>
Hello there!
<br />
I'm great, how are you?
<br />
<br />
Someone wrote:
<br />
> Greetings,
<br />
> How are you?
<br />
<br />
Someone else wrote:
<br />
> I like turtles
<br />
<br />
> Someone odd person wrote:
<br />
> > You smell like cheese
<br />
> > and now I'm hungry
<br />
<br />
and that's the end,
<br />
of all of this.
</p>
Script
$(document).ready(function(){
// link text to inform users to click to expand
var lnk = '[+]';
// variable to look for stating it's a new reply
var newrply = 'wrote:';
// reply indicator (HTML escape code for ' > ' to exclude any HTML that might be found
var isrply = '> ';
// collect html and split it into an array
var txt = $('p').html().split('<br>');
// flag showing that the text is within a reply block
var rply = false;
// cycle through each portion of text
$.each(txt, function(i){
// look for a new reply
if (this.match(newrply)){
// if within a reply and it finds a new reply, close previous
var tmp = (rply) ? '</div>' : '';
// add link
txt[i] = tmp + txt[i] + ' ' + lnk + '';
// go to next variable in array and add wrapper, this makes sure the <br> is outside the reply (formatting purposes)
txt[i+1] = '<div class="reply">' + txt[i+1];
// look for reply indicator or text that is <5 characters in length
// (in the HTML above, the array value will have carriage return plus two spaces for each <br>)
} else if (this.match(isrply) || txt[i].length < 5) {
rply = true;
} else {
rply = false;
// close the reply, add the close to the previous array element (most likely a <br>)
txt[i-1] = txt[i-1] + '</div>';
}
// close the reply at the end of the array
if(i == txt.length) {
txt[i-1] = txt[i-1] + '</div>';
}
})
// join the array and add it back
$('p').html( txt.join('<br>') );
// hide the replies
$('.reply').hide();
// add toggle view
$('.replylink').click(function(){
$(this).next().next('.reply').toggle();
return false;
})
})
I changed the link to just a '[+]' to toggle the view but I didn't bother changing it to '[-]' when the reply is open. I figured the code was getting long enough as it is for this example.
With the new code you posted, I had to make a few changes.
It will now work with multiple posts (it processes each "div.post")
It will now only find a new reply if the ">" is at the beginning of a new line
It uses the rel tag to index each reply since the .next() function of jQuery will find "" and the number of these was variable
One problem I had was with the click function, I ended up switching to .live because the click event was being triggered twice (I couldn't figure out why, but using live works).
Lastly, I left the <a name="" style="color: gray;"/> in the code, but that is not properly formatted HTML... you can't close an <a> tag this way.
New Update:
Fixed the script to work with IE, apparently IE uses <BR> instead of <br> so the split wasn't working. I ended up using $.browser.msie even though it isn't recommended. Also, the original script left unopened </div> which is why it broke in IE as well.
The rply variable I used before wasn't updating between the iterations of the each function, so I moved it's value into a hidden input tag. I tried making it global, but it just wouldn't cooperate. It's probably not the ideal way to do this, so fix/adjust as you desire.
Required HTML
<input id="replyflag" type="hidden" value="false"/>
Updated Code for IE & new pastbin posting:
$(document).ready(function(){
$('div.post').each(function(){
// link text to inform users to click to expand
var lnk = '[+]';
// variable to look for stating it's a new reply
var newrply = 'wrote:';
// reply indicator (HTML escape code for ' > ' to exclude any HTML that might be found
var isrply = '>';
// IE capitalizes the <BR>, collect html and split it into an array
var splt = ($.browser.msie) ? '<BR>' : '<br>';
var txt = $(this).find('p:eq(0)').html().split(splt);
// index of each reply in a post
var indx = 0;
// start <div> tag around contents, as the script automatically closes the tag, even without replies
txt[0] = '<div>' + txt[0];
// cycle through each portion of text
$.each(txt, function(i){
// look for a new reply
if (this.match(newrply)){
// if within a reply and it finds a new reply, close previous
var tmp = ($('#replyflag').val()) ? '</div>' : '';
// set the "within a reply flag" to true
$('#replyflag').val(true);
// increment index
indx++;
// add link, the rel attrib contains the index of the reply
txt[i] = tmp + txt[i] + ' ' + lnk + '';
// go to next variable in array and add wrapper, this makes sure the <br> is outside the reply (formatting purposes)
txt[i+1] = '<div class="reply" rel="' + indx + '">' + txt[i+1];
// look for reply indicator at the beginning of a line or text that is > 3 characters in length, if not there, turn off reply flag.
} else if (this.substring(0,4)!=isrply | this.length > 3) {
$('#replyflag').val(false);
}
// close the reply at the end of the array
if (i >= txt.length-1) {
txt[i] = txt[i] + '</div>';
}
})
// join the array and add it back
$(this).find('p:eq(0)').html( txt.join('<br>') );
// hide the replies
$('.reply').hide();
// add toggle view (using live because sometimes the click event is called twice and the toggle appears to not work)
$('.replylink').live('click',function(){
$(this).parent().find('.reply[rel=' + $(this).attr('rel') + ']').toggle();
return false;
})
})
})

Related

txt.replace </blockquote> in textarea js

I give up! I looked at many different answers. I've tried many different ways and nothing works. I want to change the </blackquote> tag to <br /> or a new line in the textarea. Alternatively, change to some other character, because later I can replace another character in PHP to <br/>. How to do it?
Working example for easy understand here: https://jsfiddle.net/jsf88/rb3xp7am/35/
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote><br />
"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐
</div>
</section>
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').text();
//txt = txt.replace('</blockquote>', '<br/>');
//txt = txt.replace(/<\/(blockquote)\>/g, "<br/>");
//txt = txt.replace(/blockquote*/g, '<br/>');
//txt = txt.replace(/(.*?)<\/blockquote>(.*?)/g, ' xxx ');
txt = txt.replace(/<\/blockquote>/gi, '<br/>')//NOT WORKING!!
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');//working great
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
});
To make it funnier, another example with changing the blackquote tag to br works without a problem. Why? can someone explain it?
//OTHER EXAMPLES WHERE CHANGE </BLACKQUOTE> to <br/> WORKING GOOD... WTF?!
string = ` <blockquote>this is a quote for comment😎 </blockquote><br />"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐`;
string = string
.replace(/<\/blockquote>/gi, ' <br /> ');//but here working! ;/
console.log(string);
you recover text with text function ('.replyMsg').text() but in that case you will have the text but with no html tag like <blockquote> so first you will have to recover the html to have the blockquote tag
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
the br tag is not interpreted in textarea so you have to change it by a new line character
don't forget to remove opened bloquote tag to get the expected result
txt = txt.replace(/<blockquote>/gi, '');
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/<\/blockquote>/gi, '\n');
txt = txt.replace(/<blockquote>/gi, '');
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
blockquote {
background-color: silver;
}
.replyMsg {
border: 2px solid green;
}
.quoteMsg {
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote>
"X" -- HERE I want BR_TAG or new line in textare a after c lick 'quote' 😐
</div>
</section>
The first problem in your code was how you were adding the event listener to the ready event. Being it something invented by jQuery, and not a native event, the correct way to do it should be as of now (v.3.3.1 the version I used in this demo) $(document).ready(()=>{/*code here*/}).
As a further reference:
https://api.jquery.com/ready/
There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes
ready before this event is attached, the handler will not be executed.
But... it's not perfectly clear how did you wish to transform your text before setting the value of the textarea. So I just better factored your logic so that you have some clear steps:
grabbing the blockquote element text content and trimming it (being the origin)
applying the transform newline to whitespace (with the regex that I left untouched)
build the final string as a template literal that will include the quote content, the meta tags wrapping it, AND anything else you wish to add like for example a new line (\n) that in this example is exacerbated by a text following it.
There's a hint in your words that put me in the position to say something superflous but still deserving an attempt: the value of a inner text is just plain text and doesn't render html content. So the <br> itself would remain as you read it and wouldn't have any rendering effect on the textarea content. That's why I focused my demonstration on putting a newline with the escaping sequence. It works both on double quoted strings and template literals: "\n" `\n`
Further notes
It seems the original approach of processing the blockquote html was preferred. It's worth saying that it was appearently a terrible strategy for several reasons:
It grabs the blockquote content as html despite that's not how it's
rendered on the page.
It takes the effort to consider the whole outerHTML removing the
wrapping blockquote tags instead of fetching directly the innerHTML.
It adds the newline as newline instead of embedding it as <br> so
at this point I ask myself if the content in the textarea was
supposed to be encoded html or not.. and the added br would then
belong to something meta?
It's harder to deal with in case you want to further customize the
string processing
But... maybe there's something I didn't get and I'm doing weak assumptions.
//since you are using the ready event with jquery, that's the correct syntax
$(document).ready(function() {
$('.quoteMsg').click(function() {
//grabs the text content of the blockquote element (trimming it)
var quoteTextContent = $(this).closest('.replyBox').find('.replyMsg').text().trim();
//performs the transform already in place in your code.. replacing newlines with white spaces
quoteTextContent = quoteTextContent.replace(/(?:\r\n|\r|\n)/g, ' '); //working great
//builds the string to set the textarea value with, using a template literal
//here you can add anything you want.. like a new line but that's just an example
const encoded = `[quote]${quoteTextContent}[/quote]\nand something following to show the new line happening`;
console.log(encoded);
$("textarea[name='quote']").val( encoded );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎
<br>
Having new lines also ... since you perform a regex transform newline=>whitespace
</blockquote><br />
</div>
</section>
Well, thanks for answers. The problem was a missing .html tag.
This script work for me almost perfect for quoting few times:
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/</g, "<");
txt = txt.replace(/>/g, ">");
txt = txt.replace(/&/g, "&");
txt = txt.replace(/"/g, '"');
txt = txt.replace(/'/g, "'");
txt = txt.replace(/<br>/g, "");
txt = txt.replace(/<hr>/g, "[hr]");
//txt = txt.replace(/<hr>/g, "\n");
txt = txt.replace(/<blockquote>/gi, '');
txt = txt.replace(/<\/blockquote>/gi, '[hr]');
txt = txt.replace(/[hr][hr]/gi, "");//not working ([][])
txt = txt.replace(/[hr][hr]/gi, "[hr]");//not working ([[hr]][[hr]])
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]\n'));
});
});
The problem here is I dont know how to change dubble [hr][hr] for nothing, because this txt = txt.replace(/[hr][hr]/g, ""); not working, so would be cool for more explain about. One more time big thanks for answers! this function .replace is not as intuitive as in PHP.
EDIT: ahh.. I think is not possible to delete this dubel, because I extra insert it two times. Nvm. I will find and del this dubel in PHP.

paragraph tags in tweet field from web page

I put together a quote machine as an exercise of freecodecamp.com. You click the button, you get a quote. Then, if you want, you can tweet the quote by clicking the "Tweet It" button. I had a lot of trouble figuring out how to get the quote to populate the tweet field. I finally just looked at someone else's code on the issue, and now it is populating.
The problem: it is populating <p> and </p> tags with every quote. Example:
"<p>When typography is on point, words become images.</p>
" Shawn Lukas
It's also annoying that the second set of quotation marks always appears on the line below next to the author's name.
I'm not sure how the tags are getting in there, but I'd like help clearing them out. Here's my code:
HTML
<div id="container">
<div class="content">
<div id="quote" class="triangle-isosceles">
<p>
<span class="msg"></span>
</p>
</div>
<p id="author"><span class="nme"></span></p>
</div>
<button type="button">Get Quote</button>
<a class="twitter-share-button" id="tweet-quote" target="_blank">
<button type="button" class="btn btn-primary">Tweet it!</button>
</a>
</div>
JS
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + "<p>— " + author + "</p>")
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + quote + '" ' + author));
});
});
</script>
I'm omitting the CSS. I can't get a jsfiddle to work (never can), but here's the CodePen link: https://codepen.io/dtarvin/pen/pePowj
Update: just found a quote with an apostrophe and got back those numbers instead of the symbol. Not sure how to handle that when the quotes are random.
Thanks!
you have "<p>— " + author + "</p>" in the append code, regarding the html entity code you need to parse the quote to switch them to the normal version. Also you might need to remove tags within the a[0].content variable. if you have no control over what is returned, you may need to do a lot more filtering to catch stuff like this.
Or if you have access to the serverside script, then use this to get the quote and return the cleansed quote.
For instance, if you visit the url https://quotesondesign.com/wp-json/posts you will see the <p> tags within the quote themselves.
So you basically need to clean the content of the content variable.
for instance to remvoe the p tag within the content string try:
var quote = a[0].content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '');
If you need these tags in to display then you could add a seperate function that on pressing the tweet it button, will do this for you.
So you have them on the browser but on tweeting its all striped and good on twitter
Try this it work
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + author);
var html = quote + author;
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent( text ));
});
});
</script>

Javascript: Add HTML to string - make a link and add it to output

New to javascript, how do I fix this problem I'm having?
I want to add an a tag to a string variable that i'm creating using a function.
The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).
When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.
This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.
How do I do this?
I tried using link() Method, which also didnt work and had similar output.
I'll only include the relevant script below, the rest works fine...
function makeMessage(){
for(i in msgArr){
stringMSG += msgArr[i];
//do not add a comma after last item
if(i < msgArr.length - 1){
stringMSG += ', ';
}
}
var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" + makeLink();
return highRiskmsg;
}
function makeLink() {
var contactLink = document.createElement("a");//create <a> tag
contactLink.setAttribute("id", "linkC");//set id att for <a> tag
contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for <a> tag
var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
contactLink.appendChild(contactLinkTxt);//append text as child of <a> tag
return contactLink;
}
It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.
You need to return a valid HTML string instead, such as: <a id=".." href="..">..</a>
The quickest way to fix your code would be just to change the return for the makeLink() function as follows:
return contactLink.outerHTML;
Using outerHTML will return the HTML string for the element, rather than the element itself.
Here is a working example
As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.
function makeMessage(){
var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";
var span = document.createElement('span');
span.appendChild(document.createTextNode(highRiskmsg));
span.appendChild(makeLink());
return span;
}
Fiddle

Replace multiple <br>'s with only one <br>

How do I use JavaScript to detect
<br>
<br>
<br>
to become one
<br>
?
I tried with:
jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");
but this is not working for me.
CSS Solution
If you want to disable the effect of multiple <br> on the page, you can do it by CSS without using JavaScript:
br + br { display: none; }
Check the jsFiddle demo.
However, this method is ideal when you are working with tags, something like this:
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
In other cases, like this:
Hello World<br /> <br />
Hello World<br /> <br />
Hello World<br /> <br />
It will fail (as CSS passes text nodes). Instead, use a JavaScript solution.
JavaScript Solution
// It's better to wait for document ready instead of window.onload().
window.onload = function () {
// Get all `br` tags, defined needed variables
var br = document.getElementsByTagName('br'),
l = br.length,
i = 0,
nextelem, elemname, include;
// Loop through tags
for (i; i < l - 1; i++) {
// This flag indentify we should hide the next element or not
include = false;
// Getting next element
nextelem = br[i].nextSibling;
// Getting element name
elemname = nextelem.nodeName.toLowerCase();
// If element name is `br`, set the flag as true.
if (elemname == 'br') {
include = true;
}
// If element name is `#text`, we face text node
else if (elemname == '#text') {
// If text node is only white space, we must pass it.
// This is because of something like this: `<br /> <br />`
if (! nextelem.data.replace(/\s+/g, '').length) {
nextelem = br[i+1];
include = true;
}
}
// If the element is flagged as true, hide it
if (include) {
nextelem.style.display = 'none';
}
}
};
Check the jsFiddle demo.
What is the point of sending HTML, which is in a form that you don't want, to the client browser and making it run JavaScript code to clean it up? This looks like a bad design.
How about fixing all your static HTML, and HTML generation, so that these superfluous <br> elements do not occur in the first place?
If you use JavaScript to modify the document object, do so for dynamic effects that cannot be achieved in any other way.
Simpler:
var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');
This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br /> or <br >).
Wouldn't something like this be the right approach:
$("br~br").remove()
EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.
This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:
$('br').each(function () {
const {nodeName} = this;
let node = this;
while (node = node.previousSibling) {
if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
break;
};
}
if (node && node !== this && node.nodeName === nodeName) {
$(node).remove();
}
});
See: https://jsfiddle.net/kov35jct/
Try this
$('body').html($('body').html().replace(/(<br>)+/g,"<br>"));
It will replace n number of <br> into one.
Demo
I would go with this:
$('body').html($('body').html().replace(/<br\W?\\?>(\W?(<br\W?\\?>)+)+/g,"<br>"));
However, after reading the comments in another post here I do consider that you should try to avoid doing this in case you can correct it in the back end.
A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace any number of <br> tags with a single tag. This works with multiple instances of multiple tags in a string.
/(<br>*)+/g
To implement this in JavaScript, you can use the String.replace method:
myString.replace(/(<br>*)+/g, "<br/>");
To replace multiple <br/> tags, add a / to the regex:
/(<br\/>*)+/g
Try this:
jQuery('body').html(
jQuery('body').html().replace(/(?:<br>\s+){3,}/ig,"\n"));
);
DEMO:
jsfiddle

Use RegEx and .replace to substitute text with user input?

I'm new to jQuery and stumbled on the concept of RegEx with .replace to make nifty text replacements.
In my form, I have some checkboxes that trigger text to appear in a textarea. There are also some user input areas as fields.
How can I use this jQuery to substitute a portion of text in certain checkboxes with the user input, but not in others? I figure using an if/else argument to trigger the RegEx and replace is key, but I don't know how to incorporate the rest?
Here is a mockup of my form:
<div style="width: 500px;"><br>
Static options:<br>
<label id="_comLine100"><input id="comLine100" name="comLines" type="checkbox"> OPTION1 </label> <br>
<label id="_comLine101"><input id="comLine101" name="comLines" type="checkbox"> OPTION2 </label> <br>
Options which can be modified by user text:<br>
<label id="_comLine102"><input id="comLine102" name="comLines" type="checkbox"> OPTION3 </label> <br>
<label id="_comLine103"><input id="comLine103" name="comLines" type="checkbox"> OPTION4</label> <br>
</div>
<br>
<input id="usrinput1" size="50" placeholder="Enter something to replace the word Text">
<br><br>
<form>
<input onclick="javascript:this.form.outPut2.focus();this.form.outPut2.select();"
value="Select all" type="button">
EDIT Here is my new script, based on suggestions below:
$(document).ready(function(){
var comLines = {
comLine100: 'Text for option1 \n',
comLine101: 'Text for option2 \n',
comLine102: 'Text for option3 \n',
comLine103: 'Text for option4 \n'
};
var mytextbox = document.getElementById('outPut2');
var chosenComm = null;
var Inputs = document.getElementsByName("comLines");
for (var i = 0; i < Inputs.length; i++) {
Inputs[i].onchange = function() {
chosenComm = this;
printComment();
};
}
function printComment(){
if(chosenComm !== null){
var chxbox=chosenComm.id;
var uinput = document.getElementById('usrinput1');
if(uinput.value!=="" && (chxbox=="comLine102" || chxbox=="comLine103")){
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
else {
mytextbox.value += comLines[chosenComm.id] + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
}
}
});
See my JSfiddle : http://jsfiddle.net/bENAY/2/
Now works as I wanted. Thanks to Eric S for the explanations and guidance!
The simple answer is replace:
mytextbox.value += comLines[chosenComm.id] + "\n";
with
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
The replace call looks for the regex in the slashes and replaces the match with the value after the comma.
$('#usrinput1').val() is using jQuery to find the dom element with ID of usrinput1 and then getting the value of it (since it's an input, it gets whatever the user has entered).
The more complete answer would mention that you probably should embrace jQuery more:
Replace the window.onload call with a $(document).ready(function(){...}) call.
Consider replacing the document.getElementById with $('#outPut2')
Consider replacing the document.getElementsByName with $(input[name=commLines]) or adding a class of comm-lines to all of those items and using $(.comm-lines)
Consider using jQuery's on function to bind the event handlers for both the inline button handlers (use a passed in function to the on call) and the Inputs[i].onchange calls.
Sorry if this sounds overly judgmental, just trying to suggest a more standard and less error-prone solution.
Still requires some tweaking, but something along the lines of this:
$('.comm-lines').on('change', printComment);
Also, I'm sure this is just a simplified example of what you're trying to accomplish, but you might consider using links or buttons instead of checkboxes. Your use of checkboxes doesn't really follow the expected experience your users have learned when using checkboxes on the web. A link more closely matches the experience most users know, and so provides less surprise to them. (Less surprise means happier users, less learning on their part and more usage.)

Categories

Resources