JavaScript - Global Variable Inside A Document.getelementbyid.innerhtml? Simple Fix??
Hey all!
Got a question I can't seem to find an answer to. I have a little JS app that is a glorified calculator which I posted the code for below. My code uses the document object to replace the html in the "content" <div> and works great. However, I want to add an inline style in order to change the background of the input (readonly field with an id of "coutput") based on either of the global variables named "MJPD" or "IJPD", (depending on the switch case selected in the user prompt at the beginning of the script.) Simplified....if the value of MJPD is less than 4.6, I want the "coutput" field's background to be red, else be green. The same goes for IJPD, except the threshold for red will be <3.83. Code and what I have tried is below. After reading the code, look below it to see what I have tried and maybe tell me what I'm doing wrong! =) Any help is greatly appreciated.......I have spent a week searching for this little answer and I can't seem to find it! Code: <script language="JavaScript"> var MJPD = 1; var IJPD = 1; function sayhello(){ // *** live test for inline JS code placement alert("IT WORKS!!! Now change me =)"); } ////////////////////////////////////////////////////// function changeScreenSize(w,h) { window.resizeTo( w,h ) } /////////////////////////////////////////////////// function iJPDCalc(form) //calculate IJPD value { var ij = parseFloat(form.IJobs.value, 10); var it = parseFloat(form.ITime.value, 10); var IJPD = 0; IJPD = (ij / it) * 8.0; form.I_JPD.value = IJPD; } ///////////////////////////////////////////////////// function mJPDCalc(form) //calculate MJPD value { var mj = parseFloat(form.MJobs.value, 10); var mt = parseFloat(form.MTime.value, 10); var MJPD = 0; MJPD = (mj / mt) * 8.0; form.M_JPD.value = MJPD; } ///////////////////////////////////////////////////// function ijpdcolor() //set bg color of coutput based on IJPD's value { if (IJPD >= 3.83) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function mjpdcolor() //set bg color of coutput based on MJPD's value { if (MJPD >= 4.6) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function startVZT3(){ var n=0; n=prompt("What would you like to do? 1: Calculate IJPD 2: Calculate MJPD 3: Exit", "Enter a value from 1-3") switch(n) { case(n="1"): document.getElementById("content").innerHTML='<FORM><h2>Combined IJPD Calculator</h2><p>Install components completed today:</p><INPUT NAME="IJobs" VALUE="3.84" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="ITime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your IJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=iJPDCalc(this.form)><p>Your current combined IJPD for today is:</p> <INPUT NAME="I_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="2"): document.getElementById("content").innerHTML='<FORM><h2>Combined MJPD Calculator</h2><p>Trouble components completed today:</p><INPUT NAME="MJobs" VALUE="4.6" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="MTime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your MJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=mJPDCalc(this.form); mjpdcolor();><p>Your current combined MJPD for today is:</p> <INPUT NAME="M_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="3"): alert('This page will now close...'); window.close(); break default: document.getElementById("content").innerHTML='<h1 style="padding-top: 40px; color: red;">You need to enter a value! Please try again...</h1>'; break } } /////////////////////////////////////////////////////// </script> </head> <body onload="changeScreenSize(825,775)"> <div id="wrapper"> <div id="sub_wrapper"> <br /> <br /> <input type="button" class="button" onclick="startVZT3()" value="Start VZT3 Web!" /> <br /><br /> <div id="content"> <h3 style="padding-top:60px;">VZT3</h3> </div> </div> <script type="text/javascript"> <!-- trying script to ensure function and dynamic update of this value - doesnt work 2/3/2010 --> document.write(mjpdcolor()); </script> </div> </body> OK, so on the last line of each case statement where it injects html code into the content div, in this code style=" background: ** ** " and in between the ** ** marks, I have added such things as <script type="text/javascript">document.write(mjpdcolor())</script> (or ijpdcolor, depending on which case I am working with). Theoretically, this should pull the value of MJPD (or IJPD), evaluate it for the if statement, then return the value of red or green and set the value of the background dynamically - but of course it doesnt. I have also tried different inline styles and even adding the css id and trying to link it to the mjpdcolor() function, but all to no avail. Can someone help me please?? Thanks everyone, your awesome! Similar TutorialsI need help creating something hard. First I need to divs that change by ONE button and when they change they say two different things and must be onclick. The other thing is there will be 4 buttons. They start black and when you click one it turns grey and when you click another it turns gray and the other one that was last clicked turns back black and same with the other two. Hi All, Im trying to get my simple js code to add some code to the html page but cant seem to (i get an error in html page); my JS code: Code: function game() { this.document.getElementById('modalone').innerHTML = "<b style='float: left; text-decoration: underline;'>Deady Teddy</b><img src='css/images/popup/close.png' style='float: right; cursor: hand;' onClick='javascript: hideModal('modalPage');'></img>"; } my html code to call this: Code: <div class="gbox"><img src="css/images/games/dt.gif" /> <a href="javascript: revealModal('modalPage'); game();">Deady Teddy </a> </div> Any Idea's? Thanks In Advance, Jamie. Quote: <html> <head> <script type="text/javascript"> var a = january var b = febuary var c = march function test() { document.getElementById("test").innerHTML=a; <!-- needs to be A on first function click, b on second, c on third, etc..^^--> } </script> </head> <body> <p id="test"></p> <!-- the <p> should go to next month upon each function --> <input type="button" value="asdf" onclick="test()" /> </body> </html> I tried to explain it pretty well in the comment tags, thanks! I am trying to pass a value to a function autosuggest() f and i but i get the error... Message: Syntax error Line: 21 Char: 29 Code: 0 ajax_autocomplete2/ajax_search_for_airport_framework.js line 21 being q = ..... how do i correctly pass a value to the function and use it in the function to get the value of an element. Code: function autosuggest(f,i) { q = document.getElementById(f).value; .... } Hello again, I seem to be having trouble with my string variable in innerHTML.. here's my code: Code: function header() { // Navigation Bar 110 var o = document.getElementById("header"); 111 var s = '<h3 style="float:left;">' 112 + ' ' 113 + '<a href="http://mattondo.com" class="link">MattOndo.Com</a></h3>' 114 + '<div style="float:right;">' 115 + '<div class="navbar">' 116 + '<a href="index.htm" class="nav" id="home">home</a>' //to homepage 117 + '<a href="about.htm" class="nav" id="about">about</a>' // to about page 118 + '<a href="construction.htm" class="nav" id="blog">blog</a>' // to blog page 119 + '<a href="contact.htm" class="nav" id="contact">contact</a>' // to contact page 120 + '</div>' 121 + '</div>'; 122 o.innerHTML = s; every time I run this using firebug, it says I have one error. That on line 122 variable o is null. And when I go through the code using firebug line by line, it gets to thevar o = document.getElementById("header"); and stores nothing in o, making it null. What could be my issue here?? Hi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike hello im trying to change a variable set outside of a function and calling the function with an onchange... i'm having problems getting the variable to change Code: <script type="text/javascript"> var price = '<?php echo $price; ?>'; function addtwo() { if(document.add.size.value == "2xl") { price = price + 2; } } </script> My code is here and it works ... However, I would like my dynamic table to show on the same page as my body and not on a new blank page. I have created a DIV and try playing around with the document.getElementById('monTab').innerHTML but it's not working out for me ... What am i missing ? Regards, Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD><TITLE>new Script - Javascript Cours 11</TITLE> <META content="text/html"; charset="UTF-8" http-equiv="content-type"> <SCRIPT type="text/javascript"> function createTable(){ var Etudiant = new Array(Number(prompt("How many Students will you put in ?",""))); document.write("<table border=\"1\">"); for (var i=0; i<Etudiant.length; i++) { Etudiant[i] = window.prompt("S'il vous plait entrez le nom d'un etudiant " + (i+1) + ".","") alert("Nice to see you "+Etudiant[i]); document.write("<td>"+Etudiant[i]+"</td>"); j = parseInt(prompt("Combien de notes voulez vous calculez ?")); for (h=0;h<j;h++){ notes[h] = parseInt(prompt("S'il vous plait entrez la "+(h+1)+" note de "+Etudiant[i])); document.write("<td>"+notes[h]+"</td>"); } document.write("<tr>"); } document.write("</tr>"); document.write("</table>"); document.getElementById('monTab').innerHTML=Etudiant; } </script> <BODY> <H1>Combien de note voulez vous cumulez ?</H1> <br> <br> <input type="button" name="btnSubmit" value="TRY IT" onclick="createTable()"> <div id="monTab" size="10"> Content should come here ...Content should come here ...Content should come here ...Content should come here ...Content should come here ...Content should come here ...Content should come here ... </div> </BODY> </HTML> Hello. I'm trying to change the text on my page dynamically using getElementById etc. Just not quite sure how to do it. Code: <script> function changeIt() { document.getElementById('change').innerHTML = '*i want the stuff below here (from 'var' to 'text')*'; } var Result= ((correct / 5) * 100) + '%'; document.write('<p>Result<b>' + score + '</b></p>'); document.write('<p>some text</p>'); </script> // <div id = "change"> *all the info I'm going to replace* </div> Just need to know how to put the variables and stuff in the 'innerhtml' part? Thanks. I am trying to have the user input data into a box on a form and when they press an "Add" button, what they typed in the input field should appear in a box below. I can get it to to work....slightly. What they typed pops up where it should be, but then it disappears. Any idea as to stop that? Here is the javascript code and the form code: Code: <script type="text/javascript"> var array = new Array(); function insert(val){ array[array.length]=val; } function show() { var string=""; for(i = 0; i < array.length; i++) { string =string+array[i]+"<br>"; } if(array.length > 0) document.getElementById('quickSearchIngList').innerHTML = string; } </script> Code: <form> <table> <th>Recipe Quick Search</th> <tr> <td class="quickSearchHeader">Ingredient:</td> </tr> <tr> <td><input type="text" name="quicksearch" size="18" id="quickSearchInput"/></td> </tr> <tr> <td class="quickSearchAddButton" id="quickSearchAddButton"><input type='image' src='images/quickAddButton.png' name='quicksearchadd' alt='Add' onclick='insert(this.form.quicksearch.value),show();'/></td> </tr> </table> </form> <div class="quickSearchIngList" id="quickSearchIngList"> </div> Code: function writeCmd() { // var div = top.buttonFrame.document.getElementById("buttonList"); for(i=0;i<arrCtr;i++) { top.buttonFrame.document.getElementById('buttonList').innerHTML = '<input type="Button" value="' + buttonTXT[i] + '" id="' + buttonIDS[i] + '" name="' + buttonIDS[i] + '" class="submenu_special" onclick="top.contentFrame.document.forms[0].submit()" /><br />'; } } So I have a basic function here, and it works... except for one thing... My arrays have multiple elements, and innerHTML only lets one button get written (the last)... How can I append, vs. replacing with this function? What I'm trying to get are the tag ids separately after I call the callback function. I've been racking my brain for far too long on this one. Here is a shorter version of what I have. I'm using the array's length to count and break into their own lines. How do i get all 9 id="hover_[index]" separately using my array length? PHP Code: var info = Array("bla_1", "bla_2", "bla_3", "bla_4", "bla_5", "bla_6", "bla_7", "bla_8", "bla_9"); function callback(results, status) { if (status == myStatus) { for (var i = 0; i < results.length; i++) { send(results[i]); } } } function send(info) { document.getElementById('results').innerHTML += "<div id='hover_"+info.length+"'>Something</div>"; hover_target = document.getElementById('hover_'+info.length);// how do i get all 9 hover_[index] separately? someEvent.addDomListener(hover_target, 'mouseover', function() { // do something }); } Thank you so much in advance, Frank I have a html file and a separate javascript file. The html file contains: <input type="reset" id = "resetButton" /> I want a message to pop up if the reset button is pressed. So in the js file I have: document.getElementById("resetButton").onclick = doAlert; doAlert is a function that simply does: alert("Do you want to reset?"); I know my separate js file is linked correctly because if I just put in alert("hello"); in the js file then it works. But if I use the document.getElementById thing in the js file, then there is an error. The error, according to the error console, says that "resetButton" is null. Can someone help me? thanks! btw, I'm totally new to programming...and I need to do this for my homework assignment I am writing some javascript that when the user clicks on a link, it hides or displays content inside a div tag. I have been trying to add some code that would only allow for one div tag to be displayed at a time. Here is where I originally got the code (http://www.willmaster.com/library/hi...-to-reveal.php) Whenever I run this code I get this error: Code: Error: document.getElementById(months[x]) is null Source File: /resources/default.js Line: 30 This is the JavaScript that runs when the user clicks the link: Code: <!-- function accordion(tid) { var x; var months = new Array(); months[0]="January"; months[1]="February"; months[2]="March"; months[3]="April"; months[4]="May"; months[5]="June"; months[6]="July"; months[7]="August"; months[8]="September"; months[9]="October"; months[10]="November"; months[11]="December"; for (x in months) { document.getElementById((months[x])).style.display = "none"; } if(document.getElementById(tid).style.display == "none") { document.getElementById(tid).style.display = ""; } else { document.getElementById(tid).style.display = "none"; }} //--> Here is where the javascript is activated from PHP Code: <a href=javascript:accordion('$month2');>$month2</a><br /> <div id='$month2' style='display: none';> Hello $month2 </div> I'm currently working on an HTML executor and would like users to be able to put javascript in their code if they wish to do so. Currently I have their input sent to an iframe via document.body.innerHTML. The problem, though, is that user submitted javascript doesn't work (with the exception of anything placed in the onload attribute of an image). Any suggestions?
Hello, I have a website that I need help with. You can visit it he http://www.shahspace.com/bow/home.html. To see what I need help with, click on the services menu item and observe the alert message that comes up. It should say "point 1". Here is the code that executes that: Code: function enableScrolling(menuName) { alert("point 1"); var menu = document.getElemenetById(menuName); alert("point 2"); ... } As you can see, there should be a second alert message that says "point 2", but there isn't. The script is crash when I try to assign to menu the object returned by document.getElementById(menuName). I have verified that menuName is correct. So why would this be crashing? To get a fuller understanding of my algorithm, I'll give you the following: The menu div: Code: <div id="services_menu" class="services_menu"> ... </div> The "services" button: Code: <td><a href="#" onclick="displayMenu('services'); return false;"><img src="services.jpg" border=0></a></td> The displayMenu() function: Code: function displayMenu(menu) { var menuName = menu + "_menu"; document.getElementById(menuName).style.display = "block"; if (itemCount(menuName) >= 12) { enableScrolling(menuName); } else { disableScrolling(menuName); } } The itemCount() function: Code: function itemCount(menuName) { var menu = document.getElementById(menuName); var divArray = menu.getElementsByTagName("div"); return divArray.length; } And the enableScrolling() function I already posted above. So essentially, when the user clicks on "service", the services menu becomes visible. If the menu contains 12 items or more, scrolling needs to be enabled. This entails setting the menu to a fixed height and allowing the user to scroll through it (scrolling, in this case, will be customized--I'm not using the div's native scrolling feature). The really odd thing is that in itemCount(), I have exactly the same line: var menu = document.getElementById(menuName); and it works fine there. Why not in my enableScrolling() function? i have the code in JS: Code: if(drop_list.value == "zed-catcher/11") { input_box.disabled=false; var catcher_id = document.getElementById('lpm_service_catcher_id'); catcher_id.value = 11; } else input_box.disabled=true; how come the line catcher_id.value = 11; is not setting the value to 11???? i get that catcher_id = null???? pleas help thanks Hello all, I am trying to use document.getElementById in FF but its not working. There is a main page. in that mainpage there is a iframe and in that iframe (id = DocFrame) there is a textbox (id="fileuploadedcnt") which i am trying to access. there is no error. ofcourse i have given name and id to the textbox. Below is the code function ConfirmCertificate(id , Project_ID , Subprogram_ID , ITCType_TI) { frm=document.mainform; //fileuploadedcnt = (document.frames("DocFrame").document.forms("upload_form").elements("fileuploadedcnt").value); filecntobj = (document.getElementsByName("fileuploadedcnt")); filecntobj = (document.getElementById("fileuploadedcnt")); alert(fileuploadedcnt); alert((filecntobj.value)); return; if (fileuploadedcnt>0) { result=confirm("Are you sure you want to confirm this certificate? "); } In the abpve case i tried both the name and id properties. with Name property i get the HTMLObj alert but again it fails if i attach value method. And for id, it doesnt work at all No errors ofcourse in both the cases What am i missing Thanks Hi ALL, I am validating a three form field which takes temperature value between 0-50, humidity 1-100 & rainfall 0-200. I am able to see expected result for temperature value but not getting correct value for humidity & rainfall(still one can insert text in it..) Here is my code-: Code: <script type="text/javascript"> function validate_form(thisform) { with (thisform) { if (validate_required(obdate,"Date must be filled out!")==false) { obdate.focus();return false;} } is_leaf_fresh = -1; for (i=0;i < thisform.is_leaf_fresh.length; i++) { if (thisform.is_leaf_fresh[i].checked == true) { //alert("coming into "+thisform.is_leaf_fresh[i].checked); is_leaf_fresh = 1; } } if ((is_leaf_fresh == -1)) { alert("You must select an option for Fresh Leaf!"); return false; } var temp_max; temp_max = document.getElementById("temperature_max").value; if (temp_max != '' ) { var numericExpression = /^[0-9]+$/; if(temp_max.match(numericExpression) && (temp_max>=0 && temp_max<=50)){ return true; } else{ alert("Max Temperature value should be Numeric & between 0 to 50"); document.getElementById("temperature_max").focus(); return false; } } var temp_min; temp_min = document.getElementById("temperature_min").value; if (temp_min != '' ) { var numericExpression = /^[0-9]+$/; if(temp_min.match(numericExpression) && (temp_min>=0 && temp_min<=50)){ return true; } else{ alert("Min Temperature value should be Numeric & between 0 to 50!"); document.getElementById("temperature_min").focus(); return false; } } var rainfall_mm; rainfall_mm = document.getElementById("rainfall_mm").value; if (rainfall_mm != '' ) { var numericExpression = /^[0-9]+$/; if(rainfall_mm.match(numericExpression) && (rainfall_mm>=20 && rainfall_mm<=50)){ return true; } else{ alert("Min Temperature value should be Numeric & between 20 to 50!"); document.getElementById("rainfall_mm").focus(); return false; } } var humidity_mm; humidity_mm = document.getElementById("humidity_mm").value; if (humidity_mm != '' ) { var numericExpression = /^[0-9]+$/; if(humidity_mm.match(numericExpression) && (humidity_mm>=20 && humidity_mm<=50)){ return true; } else{ alert("Min Temperature value should be Numeric & between 20 to 50!"); document.getElementById("humidity_mm").focus(); return false; } } } </script> Thanks in Advance!! |