Please assist me with this simple script - javascript

I am new to JavaScript and would like to ask for some help with my simple script.
What I am trying to do is to retrieve and display the values of all list item elements in the unordered list with the help of the (for) loop. I was able to get the script display all list items in the alert window one by one. But the problem is that I need values of all list elements displayed in a table row way. Like this:
Monday
Tuesday
Wednesday
.......
Here is what I have in my script:
<script language="JavaScript">
<!--
function process() {
a = document.getElementsByTagName('li')
for (i = 0; i < a.length; i++) {
alert(a[i].childNodes[0].nodeValue);
}
}
//-->
</script>
And here is HTML code:
<body>
<ul>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
</ul>
<input type="button" value="Submit" onclick="process()" />
</body>
If that's possible at all would anyone please also explain where I am wrong in my script? Why all 3 list item values can't be shown in the alert window at once?
Thanks a lot!

First, create a string variable: var all_at_once = "". Then, add the contents of the nodeValue. Finally, alert this variable:
function process(){
var a = document.getElementsByTagName('li')
var all_at_once = "";
for(i=0;i<a.length;i++){
all_at_once += a[i].childNodes[0].nodeValue + " ";
}
alert(all_at_once);
}

The alert shows repeatedly because that is what a for loop does... it loops! The loop will iterate over the array of elements returned by getElementsByTagName, executing the loop body once for each element in that array.
If you wanted to display one alert, an option would be to build up a string containing the appropriate text, and alert it afterwards:
var yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
Some other notes on your code... you should almost always declare variables with the var keyword to prevent them leaking into the global scope. You should also always end lines with semi-colons:
function process(){
var a = document.getElementsByTagName('li'),
yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
}

<script language="JavaScript">
<!--
function process(){
var data = '';
a=document.getElementsByTagName('li')
for(i=0;i<a.length;i++){
data = data + '\n' +(a[i].childNodes[0].nodeValue);
}
alert(data);
}
//-->
</script>
You need to call alert only once if you need 1 popup with all the text.

function process()
{
var a = getElementsByTagName('li'),
text = '';
for( i = 0; i < a.length; i++ )
{
text += a[i].childNodes[0].nodeValue + '\n';
}
alert( text );
}

You can process the days in whatever manner you like by storing them in an array first, and then iterating:
var days = new Array();
var a = document.getElementsByTagName('li')
for(var i = 0; i < a.length; i++) {
days.push(a[i].childNodes[0].nodeValue);
}
for (i=0; i < days.length; i++) {
// process the day
}
See: http://jsfiddle.net/jkeyes/Cfg4k/ for a working example.

These few adjustments to your function should produce the result you want. Good luck!
What changed: 1) Set up an empty string var 2) Instead of alerting each value, just append them to the string var you created earlier 3) Finally, alert the newly created (concatenated) string!
function process() {
a = document.getElementsByTagName('li');
var days = new String("");
for (i = 0; i < a.length; i++) {
days = days+(a[i].childNodes[0].nodeValue)+"\n";
}
alert(days);
}
Now I see there have been tons of answers since opening this thread... but maybe all the different solutions will help you in different ways.

Related

Search For Text in Div

I'm trying to make a runnable console command through Chrome that searches for the word "takeID", and then grabs the content immediately after it between = and & from a div class.
What I have so far doesn't work because I'm very bad at JS so any help would be appreciated. Below is what I have so far:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var searchValue = "takeID";
for(var i=0;i<iframe.length;i++){ if(iframe[i].innerHTML.indexOf(searchValue)>-1){}};
var subString = iframe.substring( iframe.lastIndexOf("=")+1, iframe.lastIndexOf("&"));
console.log(searchValue+"="+subString);
An example of the div class it would be searching would look like:
<div class="activity activity-container-html5" config="{example text;takeID=cd251erwera34a&more example text}">
There are two issues with the code. The first issue is the searchValue posts to the console as whatever is in between the takeID, and not the actual result from searching. The second issue is that the code to search between = and & doesn't work at all and I don't know why. What is wrong with the code?
I just want an output that would post to the log or a popup window saying:
takeID=cd251erwera34a
EDIT:
Something else I thought of was how would you be able to just parse the div and then search for what is in between "takeID=" and "&"? I tried this but I was getting the error "Uncaught TypeError: iframe.lastIndexOf is not a function".
var iframe=document.getElementsByClassName("activity activity-container-html5");
var subString = iframe.substring( iframe.lastIndexOf("takeId=") + 1, iframe.lastIndexOf("&") );
console.log(subString);
I looked this up and I see this is because what it is trying to process is not a string but I'm not sure why that is or how to fix it.
I don't know about you but the best would be to use json directly inside the html tag like this:
<div class="activity activity-container-html5" config="{'example':'text', 'takeID':'cd251erwera34a', 'other':''}">
Or use an array and check manually if the one you are checking is the one you want, like this:
function config(element, searchValue) {
if (element.hasAttribute('config')) {
var configData = JSON.parse(element.getAttribute('config'));
var res = "";
for (var i = 0; i < configData.length; i++) {
if (configData[i].includes(searchValue)) {
res = configData[i];
break;
}
}
return res;
}
}
el = document.getElementsByClassName('activity activity-container-html5');
for (var i = 0; i < el.length; i++) {
console.log(config(el[i], "takeID"));
}
<div class="activity activity-container-html5" config='["example=text", "takeID=cd251erwera34a", "othertext=here"]'>
The array-type (second example) is most likely to work better than the simple json one (first one).
I figured out what I needed to do. Below is working code:
var iframe=document.getElementsByClassName("activity activity-container-html5");
var div = "";
for(var i=0;i < iframe.length; i++){
div += (iframe[i].outerHTML);
}
var take = /takeID=([a-z0-9]*)&/;
var capture = div.match(take);
var matchID = capture[1];
console.log(matchID);
window.alert("takeID=" + matchID);

Show value of variable from json string

I have a for-loop:
var player = 5;
for (var i = 0; i <10; i++) {
$("#id").append('<div class="game_content_text">'+json_var[i].content+'</div>');
}
The json looks like:
"content":"<script>player</script>"
Now I only want to to write down the 5 but nothing is showing...
Edit: I simplified it. Why I have to show more code? The problem is in this lines...
For example if i show a simple text from the json ("content":"example!") it works...
For explanation:
I have a buck of personal questions in the JSON Feed.
Example: "Hello 'name_variable' how are you?"
And in the the 'name_variable' i want show random names...
If we append script tag dynamically then you need to call that code which is inside newly added script.
A script tag result cannot be assign a variable or it cannot be shown as result.
You can try following example
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
I'd like to get more code simply for the fact that I can understand the context better, because your code is rather confusing.
So apparently you try to display the value player in all your appended elements?
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + player + '</div>');
}
Otherwise, if you really need that script to be stored in the json (for some reason). I'm assuming the class "game_content_text" is only used for this.
var player = 5;
for (var i = 0, l = json_var.length; i < l; i++) {
$("#id").append('<div class="game_content_text">' + json_var[i].content + '</div>');
}
"content": "<script>$('.game_content_text').append(player);</script>"
I'm not all that familiar with jQuery, but that should work.
Also, I really do not recommend this.

How to process a text in order to create a new array with some sub strings?

I am writing a script on html, the idea is that I want to process a text that looks like this:
"TW|223SDSDr33|Archive" "Yes"
"TW|ASFFSDFSFASDFS|Name" "LOCALggr"
"TW|AFFSFSFSDFSFASDFS|AFFAckAssocCd" ""
"TW|12AFFFSDFASFSFASDFS|AFFAckCommID" "fsdf"
"TW|FSFASFFSDFSFASDFS|AFFAckLevel" "fsdf Supported"
"TW|AFFSDFAASFSA|AFFAckRqst" "No Requedfst"
"TW|AFFSDFSFASDFS|AFFAckTestInd" "Test"
"TW|sfasfsSFSAFAS|AFFAckVersion" "fsdfs"
I want to process the text to create an array called words, that contains substrings of the previous text using the pipe as separator as follows:
words=["TW,223SDSDr33,Archive" "Yes",...,"TW,sfasfsSFSAFAS,AFFAckVersion" "fsdfs"]
In order to achieve this, I tried:
var stringArray = document.getElementById("texto").value.split('\n');
document.write(stringArray.toString());
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Process every line;
}
This save my textarea to then process it, but the problem is that I don't know how to process every line in order to extract the sub strings that I want, In order to be more clear this is the complete code, I would like to appreciate any suggestion to achieve this, thanks thanks anyhow:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<textarea cols=150 rows=10 id="texto">
"TW|223SDSDr33|Archive" "Yes"
"TW|ASFFSDFSFASDFS|Name" "LOCALggr"
"TW|AFFSFSFSDFSFASDFS|AFFAckAssocCd" ""
"TW|12AFFFSDFASFSFASDFS|AFFAckCommID" "fsdf"
"TW|FSFASFFSDFSFASDFS|AFFAckLevel" "fsdf Supported"
"TW|AFFSDFAASFSA|AFFAckRqst" "No Requedfst"
"TW|AFFSDFSFASDFS|AFFAckTestInd" "Test"
"TW|sfasfsSFSAFAS|AFFAckVersion" "fsdfs"
</textarea>
<script>
var words = [];
var stringArray = document.getElementById("texto").value.split('\n');
document.write(stringArray.toString());
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Do something;
}
</script>
</body>
</html>
I used both a regular expression and Array.prototype.split. You can uncomment depending what you want to put into words.
for (var i = 0; i < arrayLength; i++) {
var line = stringArray[i];
var quotes = /"(.*?)" "(.*?)"/.exec(line);
if (quotes) {
var first = quotes[1];
var last = quotes[2];
var separated = first.split("|");
// If you want to put the array of words
words.push(separated);
// In case you want them joined with a colon
// words.push(separated.join(","));
// If you want to add the second word that was in double quotes
// words.push(last);
}
}
// Uncomment to see results
// console.log(words);

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

Adding names to an array and outputting them to a table

I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length

Categories

Resources