I'm having a hard time describing what I'm looking for.
If we pretend that we're pulling an array (I've used the .split to get user input data)
where each line represents a link.
How can I then add an anchor tagg to that link that I'm pulling?
I need to be able to put
< a href=" + thearray + ">anything< /a>.
The reason for this is that I'm dynamically creating a list.
I think that if I create two variables, one with this part
< a href="
one with the closing
and then call some sort of function that puts those two and the pulled array in between them until the list is complete.
Does this make any sense?
edit:
here's a link to the full code:
http://hem.bredband.net/noor/thecode.txt
I think you mean this:
for(var x=0;x<thearray.length;x++) {
document.write 'anything'
}
You just want to loop through the array elements, wrapping them in some HTML.
Do you mean that you want to have an array like
["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"]
and you want to turn it into
"<a href='http://www.google.com'>anything</a>
<a href='http://www.yahoo.com'>anything</a>
<a href='http://www.stackoverflow.com'>anything</a>"
?
If so, you can just do
var myArray = ["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"];
var result = "";
for (var i=0; i<myArray.length; i++) {
result += "<a href='" + myArray[i] + "'>anything</a>";
}
If not, thinking about "I want to start with X and end up with Y", with specific examples, might help you clarify your question.
Perhaps you mean something like this:
var tagStart = '<a href="',
tagEnd = '">anything</a>',
html = tagStart + thearray.join(tagEnd + tagStart) + tagEnd;
I would still suggest using a loop, though, since the code above will be unkind if thearray is empty.
I think using map and then join is going to be more readable:
function makeLink(url)
{
return "anything";
}
result = myArray.map(makeLink).join("\n");
More info about map is available at http://www.tutorialspoint.com/javascript/array_map.htm
Related
I have a little problem with this javascript code, when I add more site on the list, the page doesn't load. I have to add more than 200 site.
I'm a noob with javascript. Can someone explain what is the problem, what
I'm doing wrong?
<script language="JavaScript" type="text/javascript">
var a = new Array(
'notiziepericolose.blogspot.it',
'ilcorrieredellanotte.it',
'ilmattoquotidiano.it',
'ilfattonequotidiano.com',
'rebubblica.altervista.org',
'coriere.net'
);
var aa = a.slice();
aa.sort();
document.write("<ol>");
document.write("<b>");
for (i = 0; i < a.length; i=i+1) {
document.write('<li id="demo'+i+'">'+a[i]+'</li>');
}
document.write("</b>");
document.write("</ol>");
</script>
I guess the first thing is that document.write is very rarely used now as there a better and more efficient ways of adding things (elements, text etc) to the DOM (more on that later). In addition, in your case, what you don't realise is that document.write is not like echo or println; each time it is used it clears the document, which is probably why you're not seeing anything appear. In other words, The results of multiple document.writes are not cumulative.
The second thing is that there are better ways of "labelling" elements than with ids, particularly if there are a lot of them on the page like you'll have. Again, there are now much better ways of targetting elements, or catching events than there were ten or fifteen years ago.
So, let's talk about your code.
You can quickly create a array using the [] brackets.
var arr = [
'notiziepericolose.blogspot.it',
'ilcorrieredellanotte.it',
'ilmattoquotidiano.it',
'ilfattonequotidiano.com',
'rebubblica.altervista.org',
'coriere.net'
];
You don't have to create a copy of the array in order to sort it - it can be done in place:
arr.sort();
I'm going to keep your loop but show you a different way of concatenating strings together. Some people prefer adding strings together, but I prefer this way, and that's to create an array of the little parts of your string and then join() them together**.
// Set l as the length, and create an output array called list
for (var i = 0, l = arr.length, list = []; i < l; i++) {
// I've changed things here. I've added a class called item
// but also changed the element id to a data-id instead
var li = ['<li class="item" data-id="', i, '">', arr[i], '</li>'];
// Push the joined li array of strings into list
list.push(li.join(''));
}
Assuming you have an element on your page called "main":
HTML
<div id="main"></div>
JS
You can add the list array as an HTML string to main by using [insertAdjacentHTML] method:
var main = document.getElementById('main');
// Note that I've given the ordered list an id called list
var HTML = ['<ol id="list"><b>', list.join(''), '</b></ol>'].join('');
main.insertAdjacentHTML('beforeend', html);
OK, so that's pretty easy. But I bet you're asking how you can target the individual items in the list so that if I click on one of them it alerts what it is (or something).
Instead of adding an event listener to each list item (which we could but it can work out performatively expensive the more items you have), we're going to attach one to the ol element we added that list id to and catch events from the items as they bubble up:
var ol = document.getElementById('list');
Then an event listener is added to the list that tells us what function (checkItem) is called when a click event is raised:
ol.addEventListener('click', checkItem);
Our function uses the event (e) to find out what the event's target was (what item was clicked), and alerts its text content.
function checkItem(e) {
alert(e.target.textContent);
}
You can see all this working in this demo. Hope some of this was of some help.
** Here's another way of sorting, and looping through the array using reduce:
var list = arr.sort().reduce(function (p, c, i) {
return p.concat(['<li class="item" data-id="', i, '">', c, '</li>']);
}, []).join('');
DEMO
if ES6 is possible for you, you can do it like this:
var a = new Array(
'notiziepericolose.blogspot.it',
'ilcorrieredellanotte.it',
'ilmattoquotidiano.it',
'ilfattonequotidiano.com',
'rebubblica.altervista.org',
'coriere.net');
var aa = a.slice();
var mL = document.getElementById('mylist');
aa.sort().map(el => {
var li = document.createElement("li");
var b = document.createElement("b");
var t = document.createTextNode(el);
b.appendChild(t);
li.appendChild(b);
mL.appendChild(li);
});
<ol id="mylist"></ol>
If you're using an Array, you can use a forEach instead of a loop.
var domUpdate = '';
var websites = ['notiziepericolose.blogspot.it','ilcorrieredellanotte.it','ilmattoquotidiano.it','ilfattonequotidiano.com','rebubblica.altervista.org','coriere.net'];
websites.forEach(function(website, index){
domUpdate += '<li id="website-' + ( index + 1 ) + '"><b>' + website + '</b></li>';
});
document.getElementById('hook').innerHTML = '<ol>' + domUpdate + '</ol>';
<div id="hook"></div>
I'm thinking document.write is the wrong choice here, as it seems to be clearing the document. https://developer.mozilla.org/en-US/docs/Web/API/Document/write Probably you want to bind the new content to existing html through document.getElementById or something like that
I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/
Trying to crack this little issue I have..
I am using parse.com to store and retrieve data and I have a JSON object I am trying to retrieve a part of to append to an HTML
var tempObject = Parse.Object.extend("Dev");
var query = new Parse.Query(tempObject);
query.notEqualTo("objectId", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " receipts");
for (var i = 0; i < results.length; i++) {
var object = results[i];
$("#receipts").html(object.get('receipt_title'));
console.log(object)
//alert(object.id + ' - ' + object.get('receipt_title'));`
The result I want to show in
<div id = receipts>
<div>
Unfortunately for some reason I am getting only one line instead of the 10 that I should be getting.
I know I should loop somehow to get the results but all my tries have failed me so far.
Thanks in advance for help!
You need to add the result to the html, as right now you just replace the previous result with the next one. Instead of
$("#receipts").html(object.get('receipt_title'));
try
var html = $("#receipts").html();
$("#receipts").html(html + object.get('receipt_title'));
Also, just to mention, if you want to be efficient it might be better to just keep adding to a variable and write to the DOM only once. So:
var html = "";
for(/* Do your for loop here, thats all correct*/){
/*Do everything the same apart from the $("#receipts").html() line*/
html += object.get('receipt_title');
}
$("#receipts").html(html);
The less times you modify the DOM, the better.
From the looks of it, you are actually getting only the last line.
Try fixing it like this:
var tempObject = Parse.Object.extend("Dev");
var query = new Parse.Query(tempObject);
query.notEqualTo("objectId", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " receipts");
// Clear existing html from #receipts
$("#receipts").html("");
for (var i = 0; i < results.length; i++) {
var object = results[i];
// Adds to html of previous results (empty on first result)
$("#receipts").html($("#receipts").html() + object.get('receipt_title'));
console.log(object)
//alert(object.id + ' - ' + object.get('receipt_title'));
}
}
});
Nice.. I actually managed to solve it a bit differently:
$("#receipts").append(object.get('reciept_title'));
$("#receipts").append("<br>");
I am trying to figure out how to center the results, tried to add HTML after the append function but it broke the code for some reason
You're overwriting the contents of #receipts every time you loop through. Try this (after the first alert):
var datas = new Array();
$.each(results, function(index, data) {
datas.push('<span>'+ data.receipt_title +'</span>');
});
$("#receipts").data(options.join(''));
Play around with it a little until it does what you want it to.
How can I pass two variables on a button press? This may seem basic but I am completely stuck!
I am creating a table that has a radio button on the left side, and when you press it I want to retrieve two values. I am currently retrieving one value but I am missing the other.
Currently I am passing one value onto my onRadioButtonPress function like this:
html += "<tr><td><center><br>
<input type='radio'
onclick='onRadioButtonPress(this.value)'
name='siteChosen'
value='"+siteIDArray[i]+"'>
<center></td>";
And I am calling the function like this:
//function for on radio button press
function onRadioButtonPress(val){
//blah blah blah
}
Which is working great, but how do I add a second value of
usagePlanArray[i]
to my on onClick function? How would I change my input?
Thank you in advance!!! :) Please let me know if you have any questions, or if I missed something that would help you out!
SOLVED!
Please see the marked answer from #mplungjan. I used his alternative method that is useful for jQuerys.
value='"+siteIDArray[i]+"|"+usagePlanArray[i]+"'>
but you need to remove the newlines from the HTML too
Then in the function you can use
var vals=val.split("|");
var siteID=vals[0], usagePlan=vars[1];
Alternative - especially useful in jQUery:
html += "<tr><td><center><br><input type='radio'"+
" onclick='onRadioButtonPress(this)' name='siteChosen'"+
" data-siteid='"+siteIDArray[i]+"'"+
" data-usageplan='"+usagePlanArray[i]+"'><center></td>";
and
function onRadioButtonPress(rad) {
var siteID=rad.getAttribute("data-siteid"),
usageplan=rad.getAttribute("data-usageplan"),
}
Pass an array in JSON:
value='"+JSON.stringify(siteIDArray)+"'>
That would pass the entire Array as JSON Array string.
Passing to single values:
value='["+siteIDArray[i] + "," + usagePlanArray[i] + "]'>
or, as an object:
value='{ \"val1\":\""+siteIDArray[i] + "\",\"val2\":\"" + usagePlanArray[i] + "\"]'>
Now decode in the function
values = JSON.parse(val);
...
xyz = values[0]; // for the array
...
xyz = values.val1; // for the object
code could even be optimized, if you direct pass that to the onclick instead of the value parameter, but that might have some additional purposes.
If you are using the same index for both arrays, why not just store the index as the value and look up the desired values in the click callback?
var html= "";
var siteIDArray = [1, 5, 2, 33];
var usagePlanArray = ["unlimited", "20gb", "10gb", "5gb" ]
function arrayCombo(index){
return {siteId: siteIDArray[index], usagePlan: usagePlanArray[index]};
}
for(var i=0; i<siteIDArray.length; i++){
html += "<tr><td><center><br><input type='radio' name='siteChosen' value="+i+"><center></td>";
}
$('#content').html(html);
$('input').on('click', function(event){
//Do whatever you want with the values you are looking for here
var x = arrayCombo(this.value);
alert(x.siteId+", "+x.usagePlan);
});
Also, to demonstrate this tight-knit relationship between your arrays it would probably be better to store their values at shared indexes as properties of objects in an array.
I am very new to web development and under major deadline. I would really appreciate your help on this.
I have an array which gets created through a javascript function which runs when user clicks on a particular table on the webpage.
<tr id="table1_1_1_0">
<td>Primary</td>
</tr>
This function func_get_fields creates an array List_of_Screen_Names which has entries to be displayed.
My question is how do I display the elements of this returned array in the webpage so that each of them is a link in itself.
I found some code which works with the php arrays but not with javascript.
How can i do this ?
I tried another approach
document.write('<table border="1" cellspacing="1" cellpadding="5">')
for(i = 0; i < List_of_Screen_Names.length; i++){
document.write('<tr><td>');
document.write(List_of_Screen_Names[i]);
document.write('</td></tr>');
}
document.write('</table>');
This creates a table of strings which I think can be changed to links. But it completely wipes off the webpage and shows only the table. How to make it display within a div.
You can modify elements inner html with javascript. For example if you want to show the results in <div id="results"></div> the code would be:
var myStringArray = ["http://google.com","http://bing.com"]; //Sample array, use yours
var result = ""
for (var i = 0; i < myStringArray.length; i++) {
result = result + " <a href='" + myStringArray[i] + "'>"+ myStringArray[i] + "</a>";
}
document.getElementById('results').innerHTML = result
I hope it helps!
using "split" in javascript . it's returns array value
split
function func_get_fields(d_id)
{
var ar = d_id.split('_');
alert(ar[1]);
}
If List_of_Screen_Names is an array of links:
for(var i=0;i<List_of_Screen_Names.length;i++){
var newLink = document.createElement('a');
newLink.innerHTML = List_of_Screen_Names[i];
document.body.appendChild(newLink);
}