JavaScript - How Do I Display A Variable Returned By A Function With <fmt:message/> Tag?
Hi,
I am a newbie in JS, and have already been stuck with this problem for the whole day. Basically I want to display a var returned from a function with <fmt:message/> tag. It sounds easy, but somehow I just can't get it to be display correctly (Tried with alert() and it worked). Here is my code: ------------------------------------------------------------------------------------------- <script> function ReturnTime() { var dateobj=new Date(); if (dateobj.getSeconds()%30==0) { return dateobj.getSeconds(); } else { return dateobj.getSeconds(); } } time1 = ShowTime(); alert(time1); </script> <fmt:message key='content.currentTime'/>: <cut value="${time1}"/> ------------------------------------------------------------------------------------------------------------------------- I might have done some stupid things here. But I am very new to JS (2 days of experience so far). So please be patient. Your kind help will be very much appreciated. Regards, Robert Similar TutorialsWhenever i try to use this function it gives me either - NaN, or undefined what am i doing wrong? The objective of these functions are to change x and y coordinates into SAN (Simplified Algebraic Notation) for use in the Chess Game's DataFile (PGN file format). Live Running DHTML App: http://daomingjin.googlepages.com/ChessManager.html 140kb Zip-Archive: http://daomingjin.googlepages.com/ScoreMatev1.zip here are the functions in Question: Code: function XCoordToSAN(x) { // Convert the x coordinate of the piece to partial SAN (Simplified Algebraic Notation) for(var xCoord = 0; xCoord > xCoord * 7; xCoord++) { if(x == xCoord * BlockSize) { var SANx = xCoord; } } return SANx; } function YCoordToSAN(y) { var Letters = ["A", "B", "C", "D", "E", "F", "G", "H"]; // Convert the y coordinate of the piece to partial SAN (Simplified Algebraic Notation) for(var yCoord = 0; yCoord > yCoord * 7; yCoord++) { if(y == yCoord * BlockSize) { var SANy = Letters[yCoord]; } } return SANy; } this is how i'm calling the functions: Code: var oldPGNx = XCoordToSAN(oldXposition); var oldPGNy = YCoordToSAN(oldYposition); var newPGNx = XCoordToSAN(newXposition); var newPGNy = YCoordToSAN(newYposition); NewPGNData = oldPGNx + oldPGNy + "-" + newPGNx + newPGNy + " "; // Finally update the Data document.getElementById("PGNArea").value = OldPGNData + NewPGNData; javascript2.js Code: function displayMessage(msg) { // Open a new window var msgWindow = window.open('', 'Message'); // Write message in the new Window msgWindow.document.write(msg); // Raise this window, in case it's not visible msgWindow.focus(); } //Enter total number of questions: var totalquestions=13 var correctchoices=new Array("a","a","b","c","b","c","a","a","b","c","a","b","b"); var correctanswers=new Array("memory locations","_ underscore","x=5+5;","20","Else","lose win","ticker = ticker + 1;","Ticker = ticker + 1;","300.000","Jonathon \b","var","var counter;","var mark = 50, 70"); function gradeit(){ var actualchoices=new Array() var msg1=new Array() var correctanswersno=0 var t=0 var displaycorrectanswers="" for (q=1;q<=totalquestions;q++){ var thequestion=eval("document.Questionform.q"+q) for (c=0;c<thequestion.length;c++){ if (thequestion[c].checked==true) actualchoices[q]=thequestion[c].value } if (actualchoices[q]==correctchoices[q]){ msg1[t]=q+")"+" Correct"; correctanswersno = correctanswersno + 1; t = t + 1; } else { msg1[t]=q+")"+" Incorrect: <br>Correct Answer: "+correctchoices[q]+") "+correctanswers[q]; t = t + 1; } } for (p=0;p<=12;p++){ displaycorrectanswers+="<br>"+msg1[p]; } var msg="Sco "+correctanswersno+"/"+totalquestions+" <br><br>Marks: "+displaycorrectanswers; displayMessage(msg); } Basically on my index page it has a button which when clicked makes use of gradeit(). Currently this then used displayMessage(msg) which opens a new window and displays the message. However, what I want it to do is to open another created html page e.g. answer.html and then for this page to display the message. How do i do this? Hello All, I am a beginner javascript student and am hoping to ask for some help with a problem i am having on an assignment. I have been assigned the old Pizza Form tutorial. My form asks for customer info, select size with radio button, and select toppings with checkboxes. I created a ValidateForm() function to check if these are filled in and output a message for each field saying "please fill in field." My problem now is that on Submit I need to print out a message with customer info, selected size, and selected toppings. I have the customer info done with a var message: var message = "Name: " + name + "\n"; message += "Address: " + address + "\n"; message += "City: " + city + "\n"; message += "State: " + state + "\n"; message += "Zip: " + zip + "\n"; message += "Phone: " + phone + "\n"; message += "Email: " + email + "\n"; I know I need to add IF statements to this for the sizes and toppings but do now know where to put them. here is my whole script if that helps: function validate_form() { valid = true; if (document.PizzaForm.customer.value == "" ) { alert ( "Please fill in the 'Name' box." ); valid = true; } if (document.PizzaForm.address.value == "" ) { alert ( "Please fill in the 'Address' box." ); valid = false; } if (document.PizzaForm.city.value == "" ) { alert ( "Please fill in the 'City' box." ); valid = false; } if (document.PizzaForm.state.value == "" ) { alert ( "Please fill in the 'State' box." ); valid = false; } if (document.PizzaForm.zip.value == "" ) { alert ( "Please fill in the 'Zip' box." ); valid = false; } if (document.PizzaForm.phone.value == "" ) { alert ( "Please fill in the 'Phone' box." ); valid = false; } if (document.PizzaForm.email.value == "" ) { alert ( "Please fill in the 'Email' box." ); valid = false; } if ( ( document.PizzaForm.sizes[0].checked == false ) && ( document.PizzaForm.sizes[1].checked == false ) && ( document.PizzaForm.sizes[2].checked == false ) && ( document.PizzaForm.sizes[3].checked == false ) ) { alert ( "Please choose your Size" ); valid = false; } if ( ( document.PizzaForm.toppings[0].checked == false ) && ( document.PizzaForm.toppings[1].checked == false ) && ( document.PizzaForm.toppings[2].checked == false ) && ( document.PizzaForm.toppings[3].checked == false ) && ( document.PizzaForm.toppings[4].checked == false ) && ( document.PizzaForm.toppings[5].checked == false ) && ( document.PizzaForm.toppings[6].checked == false ) && ( document.PizzaForm.toppings[7].checked == false ) ) { alert ( "Please choose your Toppings" ); valid = false; } return valid; } function orderDetails() { var name = document.PizzaForm.customer.value; var address = document.PizzaForm.address.value; var city = document.PizzaForm.city.value; var state = document.PizzaForm.state.value; var zip = document.PizzaForm.zip.value; var phone = document.PizzaForm.phone.value; var email = document.PizzaForm.email.value; var message = "Name: " + name + "\n"; message += "Address: " + address + "\n"; message += "City: " + city + "\n"; message += "State: " + state + "\n"; message += "Zip: " + zip + "\n"; message += "Phone: " + phone + "\n"; message += "Email: " + email + "\n"; alert(message) return; } function doSubmit() { if (validate_form() == true) { orderDetails(); } } Thank you! Hi, I have php script that uploads a file. once i click upload it should display a animated GIF image or "Loading please wait" message with the backround transparent screen covering the whole page so that the user is not able to click anything during file upload. How can i do this? Could someone help me on this. Thanks in advance. Hi guys im trying to give users a warning message with javascript when the submit my login form without inserting any new data. But I can't seem to find out how to stop the form from going to the login.php here is my code. Code: <form name="te" onsubmit='login();' action='login.php' method='post'> <input name='username' maxlength='14' value='Username' type='text' /> <input name='password' maxlength='20' value='Password' type='password' /> <input type="submit" name="login" value="Login" /> </form> javascript: Code: <script type="text/javascript"> function login() { var username = document.te.username.value; var password = document.te.password.value; if (username == 'Username' || username == '') { alert('empty username!'); return false; } else { if (password == 'Password' || password == '') { alert('empty pass'); return false; } } return true; } </script> hi guys, im not very good with javascript/jquery, i have the following code: Code: <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(window).ready(function() { $("#responsecontainer").load("includes/inc-mess-jail.php", function(response, status, xhr) { }); var refreshId = setInterval(function() { $("#responsecontainer").load('includes/inc-mess-jail.php?randval='+ Math.random()); }, 9000); $.ajaxSetup({ cache: false }); }); </script> it basically updates the div tag: Code: <tr> <td colspan="2"> <div id="responsecontainer" align="center"></div> </td> </tr> i wanted to add an error message to it, that comes up underneath the <div id="responsecontainer" align="center"></div> that says "Error" with an id number next to it, then when your mouse goes over it a box comes out saying "there was a problem retrieving your information. the game will continue trying to resolve this" and then underneath where it says error i would like it to say the number of attempts it has tried to recollect the information. obviously i would only like this error message to come up, when it cannot refresh the information. Any help would be great, even pointing me in the right direction I have got a script for chat room from hotscripts however the author has left the site and I am not able to contact him. So if anyone here can guide me a bit? It is basically a php/ajax chat room script using javascript. It runs fine here is a demo: Code: http://sharinganuser.freeiz.com/Test/chat/ i have set it up properly and it is even using mysql database. My question is that I want to make log of what ever the chat is happening (even the private ones) as I am admin. I am very good at php and understand what he has done in php but I when it comes to javascript i am not a person for it. So if anyone can help me with javascript? Cause when I see the msg send button source code it shows onclick is javascript:void(0) means it is using a java script. And there are total of 4 js files used: Code: http://sharinganuser.freeiz.com/Test/chat/js/ Note: log saved in database only remains for 15 minutes or somewhat like that cause i checked the data the old conversation was gone so I am now trying to use PHP fwrite code. i know how to write and implement it but again it has to go in some js file where the send button is related and I am not sure which file and exactly where. So any help would be appreciated. Regards, Hi friends, I am trying to use the window.setTimeout feature so that a message pop-up with yes/no appears on the screen asking whether to extend the session. The actual sessions expires on 5 seconds. *If yes is clicked, the current page reloads. *If no is clicked, nothing happens. (the session will expire anyway). Many pages is open fastest, but other delays several seconds or minutes! Quote: var w = 800; var width = 800; var h = 800; var height = 800; var left =(screen.width/2)-(w/2); var top = (screen.height/2)-(h/2); window.open ("","myNewWin", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left); var a = window.setTimeout("document.form1.submit();",5000); Letchev First post - spent the whole afternoon trying to figure it out and have hit a wall. I'm trying to check a database of lotto numbers against 3 different values and have gotten it that to work. What I need is to give a feedback message if no match is found once the submit button is clicked. Code: function winCheck() { var grandPrize = $('#grandPrize').val(); var otherPrize = $('#otherPrize').val(); var addPrize = $('#addPrize').val(); var resultrange = $('#resultrange').val(); db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM entries WHERE daterange = ? ORDER BY lottonum;', [resultrange], function lottoCompare(transaction, result){ for (var i=0; i < result.rows.length; i++) { var row = result.rows.item(i); rowData = [row.lottonum]; rowStr = rowData.toString(); //the if else statements should go here. if (rowStr == grandPrize){ alert('The lotto number ' + grandPrize + ' is a jackpot winner'); } if (rowStr.slice(-7) == otherPrize.slice(-7)){ alert('The lotto number ' + rowStr + ' is a winner of $40,000'); } if (rowStr.slice(-6) == otherPrize.slice(-6)){ alert('The lotto number ' + rowStr + ' is a winner of $10,000'); } if (rowStr.slice(-5) == otherPrize.slice(-5)){ alert('The lotto number ' + rowStr + ' is a winner of $4,000'); } if (rowStr.slice(-4) == otherPrize.slice(-4)){ alert('The lotto number ' + rowStr + ' is a winner of $1,000'); } if (rowStr.slice(-3) == otherPrize.slice(-3)){ alert('The lotto number ' + rowStr + ' is a winner of $200'); } if (rowStr.slice(-3) == addPrize){ alert('The lotto number ' + rowStr + ' is a winner of $200'); } } }, errorHandler ); } ); return false; } Any help is appreciated I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. I'm trying to make a basic rss reader with a google reader-esque functionality of clicking on article names and being able to expand/collapse that article. I'm working on the expand part and am going crazy. I am having no trouble getting content and displaying it without the onclick function but when I try to integrate onclick I can just get the titles. here's the snippet. any help? Code: <!-- HTML --> <body> <div id="feeddiv"></div> <script type="text/javascript"> // feed stuff using Google Feed API function feedLoaded(result) { if (!result.error) { // Grab the container we will put the results into var container = document.getElementById('feeddiv'); container.innerHTML = ''; // Loop through the feeds, putting the titles onto the page. for (var i = 0; i < result.feed.entries.length; i++) { var entry = result.feed.entries[i]; var content = entry.content; var title = entry.title; var url = entry.link; var div = document.createElement('div'); //parentDiv for articles var articleTitle = document.createElement('div'); articleTitle.setAttribute('name', i); //set articleTitle name to article's place in array articleTitle.setAttribute('style', 'font-weight:bold;font-size:15px;'); articleTitle.innerText = title; articleTitle.onclick = function() {populate(content, title, url, i);}; div.appendChild(articleTitle); //adds title to div container.appendChild(div); //adds div to the container } } } function populate(content,title, url, i) { var article = document.getElementByName(i); //gets articleTitle //clickable title var a = document.createElement('a'); //creating title link var href = document.createElement('href'); a.setAttribute('href', url); //putting actual url into html a.setAttribute('style', 'font-size:25px;'); a.innerText = title;//still puts into html //Text var snippet = document.createElement('p'); //creates <p> to throw articles in snippet.innerHTML = content; //renders the article article.appendChild(a); article.appendChild(snippet); } </script> </body> I am fairly new to coding HTML with Javascript. I am hitting my head onto the table because i cannot figure out how to pull the variable value out in a document.write statement. Basically, I am calling a function to give me a random number between 1-4. I use that randomNumber to attach to different .jpg, descriptions, and URL's. So far, i have only got the image to display, but unable to get the link and description to display. Basically, i am trying to diplsay random ads and links like the one at the top of this page. p.s. I know I am getting the randomNumber out of my function becasue I can call a simple document.write(randomNumber) and it works. Substitute adDesc and adURL in place of randomNumber and I also get the description and link respectively. Code: <div id="main"> <div id="ads"> <script type="text/javascript"> // generate a random integer from 1 to 4 var randomNumber = randInt(4); // description of the random ad var adDesc = adDescription(randomNumber); // URL of the random ad var adURL = adLink(randomNumber); document.write("<a href=adURL >"); document.write('<img src="ad' + randomNumber + '.jpg" title=adDesc >'); document.write("</a>"); </script> </div> If you haven't guessed it, I am pretty new. Reading a book and trying to put code into action are completely different. Thanks for any help! Basically I am being restricted by a third party program that manages my email list. When a person signs up for my website it first adds them to my external email list and then to my MySQL database. In order to do this you have to pass the information of the form to the next page where you can "display" it. Nothing except this display function seems to work. So what I am trying to do is take what is outputted by this display button and store it in a javascript variable. Then transfer this variable to a form which will auto submit and start the PHP registration. I need help pulling the output of the script, right now I can either get an undefined or the entire HTML code. Is there another option? Here is my code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" > <html lang="en"> <head> <title>Raiding Professionals - Register</title> <script type="text/javascript"> var formData = function() { var query_string = (location.search) ? ((location.search.indexOf('#') != -1) ? location.search.substring(1, location.search.indexOf('#')) : location.search.substring(1)) : ''; var elements = []; if(query_string) { var pairs = query_string.split("&"); for(i in pairs) { if (typeof pairs[i] == 'string') { var tmp = pairs[i].split("="); elements[unescape(tmp[0])] = unescape(tmp[1]); } } } return { display: function(key) { if(elements[key]) { document.write(elements[key]); } else { document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->"); } } } }(); </script> </head> <body> <div id='1'><script type="text/javascript">formData.display("name (awf_first)")</script></div> <div id='2'><script type="text/javascript">formData.display("name (awf_last)")</script></div> <div id='3'><script type="text/javascript">formData.display("email")</script></div> <div id='4'><script type="text/javascript">formData.display("custom password")</script></div> <form method='post' action='register.php' name='register'> <input name='firstname' id='firstname' value='' type='text'> <input name='lastname' id='lastname' value='' type='text'> <input name='email' id='email' value='' type='text'> <input name='password' id='password' value='' type='password'> <input name='password2' id='password2' value='' type='password'> <input type='submit' value='submit'> </form> <script type='text/javascript'> var firstname = document.getElementById('1').innerHTML; ; var lastname = document.getElementById('2').innerHTML; ; var email = document.getElementById('3').innerHTML; var password = document.getElementById('4').innerHTML; ; document.getElementById("firstname").value = firstname; document.getElementById("lastname").value = lastname; document.getElementById("email").value = email; document.getElementById("password").value = password; document.getElementById("password2").value = password; </script> </body> </html> Example: Function First() { Var = x1 <--- Use this variable } Function Second() { Var = x2 Var = x1 + x2 } I know this is not the way in the example...but just making sure you know what im talking about. Hi there, Sorry that the title of this is not very descriptive but I really don't know how to describe what it is i am after. I have a variable that contains an image source. (well I hope it does) Code: var imagebackground = (this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).src; Now I need that variable to spit out the image source into where it says background, but wrapped in a url( ) Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: (THIS IS WHERE I WANT IT) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); So basically if the variable was to equal - http://www.google.co.uk/image.jpg - it would function like: Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: url(http://www.google.co.uk/image.jpg) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); I hope I have provided enough information for someone to assist me with this, but if i havent then please tell me and i will try and explain some more. Cheers, Chris Hi I'm trying to get a variable named 'html' from one function and use it in another. My JavaScript knowledge is limited, so will be grateful for any help Please see code below Code: function createMarker(point, name, label, address, type) { var marker = new LabeledMarker(point, {icon: customIcons[type], labelText: label, labelOffset: new GSize(-6, -10)}); markerGroups[type].push(marker); GEvent.addListener(marker, 'click', function() {GEvent.trigger(map,"click",null,point,point); var html = '<div>LatLng:' + name + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more info.. </a>'; marker.openMaxContentTabsHtml(html); }); return marker; } // need to get html variable from the above function into this one below GEvent.addListener(map, 'click', function(ov, latlng, ovll) { if (latlng) { var regular = '<div id="sum">LatLng:' + latlng + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more info.. </a>'; var summary = '<div id="sum">Address of' + latlng + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().restore()">less info.. </a>'; var panoDiv = document.createElement('div'); panoDiv.width = "400px"; // can be anything, will be auto resized panoDiv.height = "200px"; var tabs = [new MaxContentTab('address', '<div id="address"></div>'), new MaxContentTab('streetview', panoDiv)]; map.openMaxContentTabsHtml(latlng, regular, summary, tabs, { maxTitle: "More Information", selectedTab: 'address',// or use index 1, style: { tabOff: { backgroundColor: '#CCCCFF' } },maximized: document.getElementById('maximized').checked }); } }); Hi all, I need to pass a variable to an inner function and I got it to work but: (1) I don't know why it works (2) I don't know if it's right or optimal So, please look and comment: Code: for (var h = 1.0; h <= 3.0; h += 0.5) { ed.settings.formats['spacing' + String(h.toFixed(1))] = { 'block' : 'p', 'styles' : { 'marginBottom' : String((h - 1).toFixed(1)) + 'em' } } h = (function (h) { c.onRenderMenu.add(function (c, m) { m.add({ 'title': String(h.toFixed(1)), 'caption' : 'Set the line spacing to ' + String(h.toFixed(1)), 'onclick': function () { ed.formatter.apply('spacing' + this.title); return false; } }).setDisabled(false); }); return h; })(h); }; You can ignore a lot of the code as it doesn't factor into the question... and I know that re-ordering the code can eliminate my problem (but I can't re-order it because defining the formats MUST come before "renderMenu" or else it doesn't work - and I don't want to use two loops - one to define the formats and another to define the menu). The part that's freaking me out is this: Code: h = (function (h) { c.onRenderMenu.add(function (c, m) { m.add({ 'title': String(h.toFixed(1)), 'caption' : 'Set the line spacing to ' + String(h.toFixed(1)), 'onclick': function () { ed.formatter.apply('spacing' + this.title); return false; } }).setDisabled(false); }); return h; })(h); See the strange things I have to do to get h inside of c.onRenderMenu.add()? Is this right? Can I do it any "better" or more correctly? Thanks! -- Roger Is there any way of running a function where the name is stored as a string in a variable? I mean, the same way that PHP handles this is by appending "()" to the end of the variable. |