How to include javascript generated text into html link? - javascript

I have a javascript that displays a generated text into a div:
document.getElementById('phrase').innerHTML = phrase;
PHRASE_TEXT_GETS_SHOWN_HERE
Basically I'm trying to set up a link that will take the text and post it to twitter with a link:
Clicky for tweety
How can I include the generated text in the link?

Do you mean like:
function setPhrase(phrase) {
var url = 'http://twitter.com/home?status=' + encode(phrase);
$('#phrase').html('' + phrase + '');
}
...?
Un-jQuerying it should be straightforward enough, if that's how you roll.
This is un-jQueried:
function setPhrase(phrase) {
var url = 'http://twitter.com/home?status=' + encodeURI(phrase);
document.getElementById('phrase').innerHTML = '' + phrase + '';
}
If you didn't see my failbraining encode for encodeURI as an error you should use Firebug. It may also fail if you have more than one element with the id phrase or if you have no elements with the id phrase.

Related

I'm unable to display hyperlink via a jsp function it displays my link as text

I have below function taking text as inputs and returning text with warning symbol in a box
function showErrorMessage3(textErrorMessage1, textErrorMessage2, textInputName) {
console.log("showErrorMessage2, textErrorMessage1=[" + textErrorMessage1 + "], textErrorMessage2=["+ textErrorMessage2 +"], textInputName=[" + textInputName + "]");
$('.error_txt_input dd').text(textErrorMessage1+'\n'+textErrorMessage2);
$('.error_txt_input').css('display','block');
$('.error_txt_input').addClass(textInputName + '_Error');
}
this code should display the URL being passed in TextErrorMessage1 as a hyperlink.
But it is instead displaying it as plain text.
I'm assuming that $('.error_txt_input dd') is an <a> tag thus you can do this:
$('.error_txt_input dd').attr('href', textErrorMessage1);
if not then try this:
$('.error_txt_input dd').wrap(function() {
var link = $('<a/>');
link.attr('href', textErrorMessage1);
link.text(textErrorMessage1+'\n'+textErrorMessage2);
return link;
});

How to hard code text which are coming from javascript messages

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?
This is how we are doing in html messages.
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.
Then at the moment you want to use that alert, get that hidden text and inject it where you need it:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
You asked for another variant of this, where you currently have:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
You would then add this content again as a non-displayed span with a placeholder for the count:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
You should make sure that your translations also use the placeholder.
Then use it as follows, replacing the placeholder at run-time:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
You could make a function to deal with the replacement of such placeholders:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
And then the two examples would be written as follows:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

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

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.

Foreign letters failing when sending emails

I sometimes have to send emails in a German and I need to use ö ä ß etc... I have text written containing these letter and using alert() they appear just fine. I have code to send an email :
var link = "mailto:" + SendTo
+ "&cc= "
+ "&subject=" + escape(subjectLine)
+ "&body=" + escape(BodyText);
window.location.href = link;
When I click a button to send the email, the text is missing these foreign letters e.g gruß comes out as gru. Do I need to put anything in here to make sure these letter don't disappear?
Thank you in advance
The following articles shows how to decode the letters using javascript :
Javascript decoding html entities
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
HTML Entity Decode
Using jquery:
varTitle = $('<textarea />').html("Chris&apos; corner").text();

Categories

Resources