I would need to get only the text from certain array. So I need to parse it. I have the following code:
for(var x=0;x<contentArray.length;x++){
markup += '<td>'+contentArray[x+1] +'</td>';
x++;
}
Which gives the following output:
<td><c><ul><li>The content text</li></ul></c></td>
And it loks on browser like this:
<ul><li>The content text</li></ul>
Now I would like to get only the text (The content text& in this case). How am I able to do tit?
You can use this function to unescape HTML (stolen from the Prototype source code):
function unescapeHTML(html) {
return html
.replace(/</g,'<')
.replace(/>/g,'>')
.replace(/&/g,'&');
}
You can then use jQuery's parsing capability to get the text from the tags:
for(var x=0;x<contentArray.length;x++){
var $el = $(unescapeHTML(contentArray[x+1])).find('li'); //use the unescaped HTML to construct a jQuery object and find the li tag within it
markup += '<td>' + $el.text() + '</td>'; // get the text from the jQuery object and insert it into the fragment
x++;
}
Related
I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/
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));
I need to assign an <a> tag to a textarea value, separated with a comma. I'm trying to insert email IDs I get from a response of an ajax request. How do I achieve this using JS?
I tried using:
$('reminder_email').value += "<a href='#' id='+id'>+email+</a>";
Assuming that 'reminder_email' is the id of the relevant textarea, and that the response is an array of emails:
var emailAddressesArray = ['emailAddress#host.tld', 'emailAddress2#otherHost.tld'];
$('#reminder_email').val(emailAddressesArray.join(', '));
JS Fiddle demo.
If, on the other hand, you're trying to create the HTML of an a element with a mailto protocol (for copying/pasting elsewhere):
var email = 'emailAddress#host.tld';
$('#reminder_email').val('' + email + '');
JS Fiddle demo.
Note that you can't create clickable links within a textarea, as they can't contain HTML (just text).
If, though, you have an object from which to create your value:
var email = [{
'address': 'emailAddress#host.tld',
'id': 'emailOne',
'text': 'UserNameOne'
}, {
'address': 'anotherAddress#host2.tld',
'id': 'emailTwo',
'text': 'UserNameTwo'
}];
$('#reminder_email').val(function(_, v){
for (var i = 0, len = email.length; i < len; i++){
v += '' + email[i].text + ', ';
}
return v.slice(0, v.length - 2);
});
JS Fiddle demo.
The reason your code:
$('reminder_email').value += '<a href='#' id='+id'>+email+</a>;
didn't work is twofold:
$('reminder_email') is a selector looking for reminder_email tags (which don't exist); assuming that it's an id you're looking for you'll need to use: $('#reminder_email') instead,
A jQuery object/collection has no .value property, instead use the val() method (without arguments to get the current value, or with an argument to set a new value).
hoping you have jquery imported, try this:
$('reminder_email').val("<a href='#' id='"+id+"'>" + email + "</a>");
are you appending it? why do you use += ?
Here's my problem:
I have a JavaScript function inside of a JSP that looks like this:
<script type="text/javascript">
function generateTable()
{
var temp = '';
temp = temp + '<logic:iterate name="dataList" id="dto" indexId="dtoIndex" >';
temp = temp + '<logic:equal name="dtoIndex" value="0">';
temp = temp + '<thead>';
temp = temp + '<tr class="topexpression7"></tr></thead><tbody></logic:equal>';
temp = temp + '<tr>';
var propertyArray = new Array('"title"','"jDate"','"employeeId"','"employeeName"');
var arrayLength = propertyArray.length;
var html = '';
var i=0;
for (i=0; i<arrayLength; i++)
{
if (i == 2)
{
// left
html = html + '<logic:present name="dto" property=' + propertyArray[i] + '><td class="left"> <bean:write name="dto" property=' + propertyArray[i] + '/></td></logic:present>';
}
else if (i == 3)
{
// Only applies to this property
html = html + '<logic:present name="dto" property="employeeName">';
html = html + '<td class="left" style="white-space:nowrap;"> ';
html = html + '<nobr><bean:write name="dto" property="employeeName"/>';
html = html + '</nobr></td></logic:present>';
}
else
{
// center
html = html + '<logic:present name="dto" property=' + propertyArray[i] + '><td class="center"> <bean:write name="dto" property=' + propertyArray[i] + '/></td></logic:present>';
}
}
temp = temp + html + '</logic:iterate></tbody>';
// Write out the HTML
document.writeln(temp);
}
</script>
If I hard code the property like where (i == 3), it works fine. Renders as expected.
But by trying to parse a string dynamically (where i <> 3), the string var "html" is null every time. Admittedly, my JavaScript is average at best. I'm sure it's an easy fix, but darned if I can figure it out!
P.S. Long story as to why I'm going this route, and I'll spare you the story (you're welcome). I just want to know why the variable propertyArray[i] isn't working.
The JSP is rendered on the server and JavaScript on the client browser, but to render properly the JSP tags should be well formed, i.e. have all necessary attributes with valid values, begin and close tag, etc. But not all your tags are valid. First your JSP compiled on the server and it can't process the bad JSP tags. When i != 3 you have that bad JSP tags. When the JSP is compiled the JavaScript code is used like a content, it has less meaning for the JSP compiler because it is looking on the tags that correspond a JSP syntax. Looking by the eyes of the JSP compiler you'll see the logic:present tag has attribute property but has not a value because propertyArray[i] is not evaluated as a JSP expression, it simply breaks the tag boundary. So the Tag is not compiled properly. If you place JSP tags into JavaScript code make sure they're consistent.
propertyArray[i] is working; it's the rest of it that isn't (and won't).
JSP tags don't execute on the client side; HTML generated in JavaScript must not include JSP tags (unless you don't care if they don't run). Instead, the JavaScript itself must be generated using tags on the server side before it's sent to the browser.
In this case, however, it might be best to just render HTML returned from an Ajax request, though, depending on what you're really trying to do, or create it all in JSP (not JS), etc.
My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!