JavaScript - Problem With Line Break
Hi everyone
I am trying to complete some code involving a while loop. It's actually part of an assignment. Although the code is outputting ALMOST correctly there is one thing bugging me. Here is the code: Code: playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber] + '<BR>'); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; while(playersPosition<80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); Now, from what I can see I think it's correct. But if if(indexOfNumber != -1) is not executed I get the following: Sco 2, Squa 2 Sco 4, Squa 6 OK Sco 4, Squa 6 should be on a new line below Sco 2, Squa 2 but no matter where I add the line break, it just will not do it. Can somebody please point me in the right direction as I am wasting so much time on this silly little problem Many thanks in advance EDIT: Ok after further fiddling with the code I entered document.write('<BR>'); in the required place and removed + '<BR>' from document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber] + '<BR>'); This has fixed the problem so I'm happy now. Sorry if I wasted anybodies time. I can't believe I have spent over 7 hours trying to figure this out! Similar TutorialsI have these line of javascript: Code: $(document).ready(function () { /*$('#first').focus(); $(this).keyup(function (e) { if (e.keyCode == 13) { generate(); } });*/ }); function generate() { if($("input[name='name']").val().length > 1) { fi = $("input[name='name']").val().substring(0,1).toUpperCase(); var sl = ["Cool "]; var sl2 = ["Hand "]; var sl3 = ["Luke",]; { var i = Math.floor(Math.random() * sl.length); var j = Math.floor(Math.random() * sl2.length); var k = Math.floor(Math.random() * sl3.length); var nick = sl[i] + sl2[j] + sl3[k]; } { $("#answer").text("Your Name Is: " +nick); $("#answer").fadeIn("slow"); } ; } } I would like for it to return: Your Name Is: Cool Hand Luke I want the "Cool Hand Luke" to be on a separate line but I don't know how to put a linebreak in the .text string. Is this something somebody could tell me how to do? Where in the line: Code: $("#answer").text("Your Name Is: " +nick); Do I put (<br>) Hello: First post here on CS ... I am wondering why my code will not write a new line or line break. This is fine: Code: <script> document.write("Hello and welcome to javascript!"); </script> But when I try to put a message on two lines, it does not work. The book I'm reading and several websites have stated the below codes will work, but neither do: Code: <script> document.write("Hello and welcome to javascript! \n"); document.write("It is a tricky language to learn!") </script> Code: <script> document.writeln("Hello and welcome to javascript!"); document.writeln("It is a tricky language to learn!") </script> Am I missing something? Hey guys. I'm working on a "Preview Post" function. When the Preview Post button is clicked, it should reload the page, show the preview above the textarea, then send the text back to the textarea so the user can keep working. It works until I move to a second line. If there are line breaks they don't get shown in the preview. Also, the text isn't sent back to the textarea. I have a pair of functions that are supposed to handle the input string. The first function records the input when typing, and the second function picks up the post to print as a preview: You can see what I mean he Code: function preview() { var preview = window.document.postform.inputpost.value; window.document.hidden.inputpreview.value = preview; } function copypreview() { var copypreview = '<?php echo $_POST[inputpreview]; ?>'; window.document.postform.inputpost.value = copypreview; } Here's how I use them: Code: <body onload='copypreview();'> <?php include("navbar.php"); ?> <?php if ($_GET[preview]) { echo "<table id=blog><tr><td>"; echo $_POST[inputpreview]; echo "</td></tr></table>"; } ?> <form name="postform" action="submitpost.php" method="post"> Post Title <input size="40" type="text" name="inputtitle" id="inputtitle"> <?php include("tagbar.php"); ?> <textarea onchange="preview();" cols="101" rows="20" id="inputpost" name="inputpost"></textarea> <div align=center> <input type="submit" value="Submit"/> </form> <form name="hidden" method="post" action="addpost.php?preview=1"> <input type="hidden" name="inputpreview"> <input type="submit" onClick="preview();" value="Preview Post"/> </form> Sorry I know it's a lot of code. I tried to make it as readable as possible. Can someone tell me how to fix this? I thought I might have to find a way to insert <br> tags when the user hits the Enter key, but I could have sworn this thing was working with line breaks before. I have this Javascript and I am wanting to create a line break between the tweet and the time it was posted, here is the javascript, I am guessing I need to insert the <BR> tag somewhere but just not sure where? Thanks function twitterCallback2(twitters) { var statusHTML = []; for (var i=0; i<twitters.length; i++){ var username = twitters[i].user.screen_name; var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) { return '<a href="'+url+'">'+url+'</a>'; }).replace(/\B@([_a-z0-9]+)/ig, function(reply) { return reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>'; }); statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id_str+'">'+relative_time(twitters[i].created_at)+'</a></li>'); } document.getElementById('twitter_update_list').innerHTML = statusHTML.join(''); } function relative_time(time_value) { var values = time_value.split(" "); time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3]; var parsed_date = Date.parse(time_value); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); delta = delta + (relative_to.getTimezoneOffset() * 60); if (delta < 60) { return 'less than a minute ago'; } else if(delta < 120) { return '<br>about a minute ago'; } else if(delta < (60*60)) { return (parseInt(delta / 60)).toString() + ' minutes ago'; } else if(delta < (120*60)) { return 'about an hour ago'; } else if(delta < (24*60*60)) { return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { return '1 day ago'; } else { return (parseInt(delta / 86400)).toString() + ' days ago'; } } Hi there, I am working on javascript, the problem i have faced here is, i am unable to break the line in javascript. Actually i am using a javascript to open Microsoft Outlook Express, And in the body text i am sending some value like "Name and Address(Shown in code)". I want after task it should break the line and the value of Address will start from new line. But i am unable to do that. The code i have used is given below. Code: // JScript File function EmailIt(emailTO,strAddress,strName) { var daReferrer = document.referrer; var task = escape(document.URLUnencoded); var issue_id = document.URLUnencoded.split("="); var email = emailTO; var Address = strAddress; var Name = strName; var subject = "Issue Task number is " + issue_id[issue_id.length-1] + " - " + Address ; var body_message = "Name "+ Name + " <br />\r\n " + " Address " + Address; var mailto_link = 'mailto:'+email+'?subject='+subject+'&body='+body_message; win = window.open(mailto_link); if (win && win.open &&!win.closed) win.close(); } Also i have used following syntax to break the line: //body_message += '<br />\r\n'; //body_message += " "; //body_message += "\"\n\"";. But didn't got succeed. Can anybody help me to come out of this problem. Regards Vimal kumar Madhepura, Bihar Hey guys I export data from Javascript to Xml file. I have tried several ways to break a line in xml file like document.write("<br/>"); or document.writeln(); etc, but seem it is impossible. Maybe you can give me a solution...... Look at below: XML File: <?xml version="1.0"?> <DATA> <Cust>< Select>Debit Card</Select> </Cust ><Cust>[ User>Jan</User ></Cust> <DATA> I want to break <Cust> from another <Cust>. Javascript: function ok_click() { var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.6.0"); xmlDoc.async = false; xmlDoc.load("data.xml"); if (xmlDoc.readyState == 4 && xmlDoc.parseError.errorCode == 0) { var root = xmlDoc.documentElement; var e1 = document.getElementById("Select1"); var _account_type = xmlDoc.createTextNode(e1.options[e1.selectedIndex].value); var e2 = document.getElementById("Select2"); var _user = xmlDoc.createTextNode(e2.options[e2.selectedIndex].value); var account_type = xmlDoc.createNode(1, "Select", ""); var user = xmlDoc.createNode(1, "User", ""); account_type.appendChild(_account_type); user.appendChild(_user); var cust = xmlDoc.createNode(1, "Cust", ""); cust.appendChild(account_type); document.write("<br/>"); cust.appendChild(user); root.appendChild(cust); SaveXML(xmlDoc, "data.xml"); alert("Save!"); } } Your help would much appreciated Thanks Natz Hi there, I could probably say that I'm some sort of "game developer" as we're modifying an old (but great) hockey title that has html frontend. http://z6.invisionfree.com/flyermani...showtopic=1864 My JS skills suck though... I have millions of great ideas but because of my very limited skills I run into all kinds of obstacles all the time. This is yet another. I'd like to redesign the scoring summary layout in the game... so I'm trying to create a scoring line that would show the goal scorers like this: Atlanta Scoring: Antropov (1), Reasoner (1) But currently I'm always getting a line break and I get the scorers like this: Antropov (1) Reasoner (1) etc. Screenshot: My code must be sloppy as hell though: This shows the scorers: Code: var sDataHTML4 = "" var aHeaderText = new Array(nhlMsg(" Goal assist") , nhlMsg("Team"), nhlMsg("# Assists", true) ); var aHeaderWidth = new Array( 300 , 120, 50); var sHeaderHTML4 = createHeaderRow( aHeaderText , aHeaderWidth ); for ( var i = 0; i < oAwayLastGame.nNumPlayers; i++ ) { if (oAwayLastGame.aPlayerStats[i].nAssists > 0) sDataHTML4 += createDataRow4( oManagerInterface.GetPlayerFullName( oAwayLastGame.aPlayerStats[i].nPlayerID), ( oManagerInterface.GetTeamShortName(oAwayLastGame.nTeamID)), oAwayLastGame.aPlayerStats[i].nAssists) ; } return createTable( sHeaderHTML + sDataHTML + sDataHTML2 + sHeaderHTML3 + sDataHTML4 + sDataHTML3 + sGoals ); Datarow arguments: Code: function createDataRow4( args ) { var sHTML = "<tr>"; var nNumArgs = arguments.length; for( nIndex = 0 ; nIndex < nNumArgs ; nIndex++) { (nIndex == 0 ) ? sHTML += "<td class=\"fourthDataCell\">" + arguments[nIndex] + "</td>" :sHTML += "<td class=\"data2\">(" + arguments[nIndex] + ")</td>" } return sHTML += "</tr>"; } What the heck I have to do make the scorers to show all in the same line? Does "create datarow" automatically define them in one separate row? The answer must be simple but I simply can't figure it out... I have tried to Google this for days now. Thanks. Hi guys, just a quick question about a line break in JavaScript, where would I do it? If you see I have two math operators here and want them to be on two separate lines, were do I put the line break? Thanks Code: <!doctype html> <head> </head> <body> <script type="text/javascript"> var apples = 4+76; document.write(apples); var multiple = 54*11; document.write(multiple); </script> </body> </html> Hello Coding Forums, I have a list of pub skittle players and I want a definite gap after two iterations. So.. The Red Lion ...... John and his Mrs The Two Pigs ......Martin and his mate The next pub ...... the next pair The next pub ...... the next pair Below is what I have so far : Code: var pubs = new Array('The Red Lion','The White Hart','The Cross Keys','North End Club','The Three Crowns','The British Legion','The Hare and Hounds','The Royal Oak'); var teamMembers = new Array ('Joan & Richard','Steve & Colin','Brian & Martin','Alice & Moyra',' Kirsty & Ben',' Lorri & Mark','Paul & Andy','Finchey & Sue'); for (var cplCount = 0; cplCount < teamMembers.length; cplCount = cplCount + 1) { document.write('The venue will be ' + pubs[cplCount] + ' and the players are ' + teamMembers[cplCount] + '<BR>'); } As you can see it's one big list at the moment. Any help would be greatly appreciated Morris L is there a way to make a javascript <br/> ??
i have a program which gets values from different arrays and displays them on screen. how do i insert a break every 5 lines so its easier to read?
Hey everyone, below is a very simple jquery slideshow script which functions exactly as it should. BUT, if I link an image in the DIV set (See proposed change section) the slideshow breaks, instead of cycling through each image in turn it keeps trying to cycle the first image over and over. What am i not getting here? Script linking in header of HTML page Code: <script type="text/javascript" src="script/jquery-1.2.6.min.js"></script> <script type="text/javascript" src="script/slideshowsc.js"></script> CSS on HTML controlling DIV position/opacity Code: #slideshow { position:relative; height:186px; } #slideshow IMG { position:absolute; top:0; left:20px; z-index:8; opacity:0.0; } #slideshow IMG.active { z-index:10; opacity:1.0; } #slideshow IMG.last-active { z-index:9; } DIV setup in HTML page Code: <div id="slideshow" style="padding-top:15px; text-align:center; width:540px; padding-bottom:43px;"> <img src="images/did-u-know1.png" width="499" height="186" border="0" class="active" /> <img src="images/did-u-know2.png" width="499" height="186" /> <img src="images/did-u-know3.png" width="499" height="186" /> </div> PROPOSED CHANGE IN DIV CODE HERE Code: <div id="slideshow" style="padding-top:15px; text-align:center; width:540px; padding-bottom:43px;"> <a href="whatever.html><img src="images/did-u-know1.png" width="499" height="186" border="0" class="active" border="0" /></a> <img src="images/did-u-know2.png" width="499" height="186" /> <img src="images/did-u-know3.png" width="499" height="186" /> </div> Finally, Javascript / Jquery fired through body tag onload Code: function slideSwitch() { var $active = $('#slideshow IMG.active'); if ( $active.length == 0 ) $active = $('#slideshow IMG:last'); // use this to pull the images in the order they appear in the markup var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first'); // uncomment the 3 lines below to pull the images in random order // var $sibs = $active.siblings(); // var rndNum = Math.floor(Math.random() * $sibs.length ); // var $next = $( $sibs[ rndNum ] ); $active.addClass('last-active'); $next.css({opacity: 0.0}) .addClass('active') .animate({opacity: 1.0}, 1000, function() { $active.removeClass('active last-active'); }); } $(function() { setInterval( "slideSwitch()", 8000 ); }); Hello Coders, I am not a coder so this is a problem to me to solve this error. I checked javascript at JSLint and it droped me a error: Code: Problem at line 29 character 17: Unreachable 'break' after 'return'. break; Problem at line 50 character 21: Unreachable 'break' after 'return'. break; and the script is: Code: <html> <head> <title></title> </head> <body> <script type="text/javascript"> function keyDown(key) { if (currentstep == "1") { switch (key) { case 17: if (key1pressed == "") { changeKeyStyle("key1", "down"); key1pressed = "1"; showobj("step2"); } break; case 67: if (key2pressed == "") { changeKeyStyle("key2", "down"); key2pressed = "1"; } if (key1pressed == "1" && key2pressed == "1") { step1Complete(); return false; break; } break; default: } } else if (currentstep == "2") { switch (key) { case 18: if (key1pressed == "") { changeKeyStyle("key1", "down"); key1pressed = "1"; showobj("step2"); } break; case 68: if (key2pressed == "") { changeKeyStyle("key2", "down"); key2pressed = "1"; if (key1pressed == "1" && key2pressed == "1") { step2complete(); return false; break; } } break; default: } } } </script> </body> </html> Thank you for all your help, Arnas Hello, I'm using simple form validation, found online, to check certain fields before submitting. The problem is that, although the script detects the error/missing field/wrong syntax and pops up the corresponding alert, after the user presses OK in the alert box the script continues and sends the form - which of course is not valid. HTML PART: Code: <input name="Submit" type="submit" class="textfield" value="Register" onclick="checkitems();"> JAVASCRIPT PART: Code: function checkitems() { valid = true; if ( document.registration.Onoma.value == "" ) { alert ( "Please enter your name." ); return false; } if ( document.registration.HlekDieuthinsi.value == "" ) { alert ( "Please enter your email." ); return false; } var e=document.registration.HlekDieuthinsi.value var emailFilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i if (!(emailFilter.test(e))) { alert ( "The email address you entered is not valid." ); return false; } return valid; } Hiya I have created a small html with some javascript that runs through and picks up <a hrefs> and opens the links in new tabs (to check raw html for dead links) It also pastes the links on the same page, thing is, in my loop as you'll see below it pastes the link then I try to <br /> to display the next underneath like so (on the same page): Link Link Basically it works perfect for link 1 but it doesnt loop back around and grab the 2nd link. Ideally I would like numbered links with a total at the bottom, I've been sitting trying to do it for about 3 hours now Heres my code, will explain much faster if you run it: Code: <HTML> <HEAD> <TITLE> New Document </TITLE> <script type="text/javascript"> <!-- function open_links() { document.getElementById("htmlDiv").innerHTML = document.getElementById("htmlArea").value; a = document.getElementById("htmlDiv").getElementsByTagName("a"); for(i=0; i < a.length; i++) { window.open(a[i].href); var divReport = document.getElementById("report"); report.innerHTML = (a[i].href); document.report.write(item ); document.write("<br\/>"); } } --> </script> </HEAD> <BODY> <div> <textarea id="htmlArea" cols=50 rows=20></textarea> <button onclick="open_links();">Check Links</button> <div style="font-family: Lucida Console; color: rgb(255, 255, 255); font-size: 12px; background: none repeat scroll 0% 0% black; width: 523px;" id="report"> </div> </div> <div id="htmlDiv" style="display: none;"></div> </BODY> </HTML> If anyone has an idea why it wont run I'd be greatful, because what I can do is make it work fine but it makes a new page, I want it on the same page below the text area Thanks in advance for any help! Liam Hello! =) I am using tinybox2 to make a modal window, which now I have loading correctly. =) thank you! the modal window loads as an iframe, but I have two image links inside the modal window. One I'd like to open in a new window (i got that one!), the other image I'd like to be treated the same as the X button and have it close the modal window. this is the body onload in the main document Code: <body onload="TINY.box.show({iframe:'modal.html',boxid:'frameless',width:750,height:450,fixed:false,maskid:'bluemask',maskopacity:70,closejs:function(){closeJS()}})"> <script language="JavaScript1.2">mmLoadMenus();</script> these are two lines for closing in the CSS file Code: .tclose {position:absolute; top:0px; right:0px; width:30px; height:30px; cursor:pointer; background:url(images/close.png) no-repeat} .tclose:hover {background-position:0 -30px} Thanks once again in advance! carrie Hi, I came across this thread and I've decided to use jmrker's code. Code: <html> <head> <title>Clock Example</title> <script type="text/javascript"> function startTime() { var d=(new Date); var str = d.toLocaleTimeString().toLowerCase().replace(' ',''); var tmp = d.toLocaleDateString().split(' '); var dm = d.getDate(); switch (dm) { case 1: case 21: case 31: dm += 'st'; break; case 2: case 22: dm += 'nd'; break; case 3: case 23: dm += 'rd'; break; default: dm += 'th'; break; } str += ' '+tmp[0].substr(0,3)+', '+tmp[1].substr(0,3)+' '+dm+', '+tmp[3]; startTime.out.innerHTML = str; } onload = function(){ startTime.out=document.getElementById("time"); setInterval(startTime, 1000); }; </script> <body> <div id="time"></div> </body> </html> However, I would like to modify some elements. Right now the date and time are displayed in this format: Quote: 9:58:45am Sat, Feb 26th, 2011 I would like to know how to change it to look like this: Quote: SAT 09:58:45 AM (for example) Could someone please break down the code and let me know what I need to change to get this to work? Or, if it's less trouble, just change the code for me? Thanks, I appreciate your time. Is there a method for breaking out of frames that's truly cross-browser compatible? I've seen a ton of examples on how to do this, but I'm not sure which method works the best. Thanks! Hi there, I am trying to pick the larger of 5 numbers and sometimes there is a tie. I would like to prioritize variable c1 if there is a tie. This data is from a quiz I am writing. var c1 = 2; // Takes priority if there is a tie. var c2 = 1; var c3 = 2; var c4 = 0; var c5 = 0; |