JavaScript - Using Array Values To Declare An Buttons Onclick
So here's my problem. I have a long list of buttons that I want to declare their onclick with values from an array. It looks something like this. It seems simple but obviously there's something that I'm not seeing that isn't allowing this to run.Here's what the code looks like
Code: <html> <body> <form name="form1"> <input type="button" name="one"> <input type="button" name="two"> <input type="button" name="three"> </form> <script> function hello() { .... .... } goodbye = ["one","two","three"] for(i=0;i< 3; i++) { document.form1.goodbye[i].onclick=hello; } If anybody could help me out with this I would greatly appreciate it. Similar TutorialsHow do i declare an empty array? I need to iterate through a group of arrays and search for a user-chosen word every time. The problem is i can't declare how many array elements will be needed, such as: new array = (12), because some words inside my arrays, occur more than others. So i need to decalare an empty array with x number of possible values. Can this be done? I'm trying to set up a post preview to use before submitting a post. I need button 1 to open a pop-up with the preview of the post, and then button 2 should submit the post after the poster is satisfied. With the code below, when either button is clicked, each work as expected. The problem I'm having is, after the preview (OnButton1) is clicked, the submit button (OnButton2) will only open in a new tab, and not submit to the opened page from where it is being executed. This could lead to many double posts, if someone who's not sure what is going on, keeps clicking the submit button. I am wondering if there is a target "_self", or another method to make this work. I'm very happy with the preview window popping up, as it should, but will try any suggestions that are offered. function OnButton1() { var popUp = window.open ('','popUp','scrollbars=yes,resizable=yes,width=800, height=450'); document.form.action = "index.php?page=Preview" document.form.target = "popUp"; // Open in a new window document.form.preview(); // Submit the page return true; } function OnButton2() { document.form.action = "index.php?page=post" document.form.submit(); // Submit the page return true; } Hi, I have a row of buttons that are made by innerhtml using this code: Code: sidebar_html += '<div id="button"><input type="button" onclick="toggleRun('+poly_num+')" value="Start Bus" id="runBtn'+poly_num+'" style="width:120px; height:24px; text-align:center"></div><br />'; to fire this function: Code: function toggleRun(poly_num){ var btn = document.getElementById('runBtn'+poly_num); if (document.getElementById('runBtn'+poly_num).onclick) { if (run){ run=false; document.getElementById('runBtn'+poly_num).value="Reload Page"; startAnimation(poly_num); } else { run=true; document.getElementById('runBtn'+poly_num).value="Reload Page"; window.location.reload(); } } } the function can only run once, so the idea is that the button either runs it the first time or reloads the page. at the moment, the way it's working is that the button that's clicked changes its value to "Reload Page" but the others keep their original value, even though it reloads if you click them. So I'd like a way to change the value of the rest of the buttons when one is clicked. Is that possible? Here's the page if I didn't explain myself well enough. Hi, I have 4 radio buttons with separate div(s) I need to click on each radio button to show particular div(s) but I am not getting correct result Lease help HTML Code ---------- <input type="radio" name="list_prefer_c" id="list_prefer_c" value="1" onClick=\"get_radio_value(1);\" > <input type="radio" name="list_prefer_c" id="list_prefer_c" value="2" onClick=\"get_radio_value(2);\" > <input type="radio" name="list_prefer_c" id="list_prefer_c" value="3" onClick=\"get_radio_value(3);\" > <input type="radio" name="list_prefer_c" id="list_prefer_c" value="4" onClick=\"get_radio_value(4);\" > <div id="div1" style="display:none"> Facilities Management </div> <div id="div2" style="display:none"> <div style="font-weight:bold">Facilities Management, Contracting, MEP, Hydraulic Valves, trading etc… </div> <div id="div3" style="background-color:#00B0F0;display:none"> Facilities Management, Contracting, MEP, Hydraulic Valves, trading etc… </div> <div id="div4" style="background-color:#00B0F0;display:none"> Facilities Management,Contracting, MEP, Hydraulic Valves, Plumping, LV Switching, Fire alarm & Fire Fighting Trading etc… </div> JSCode -------- function toggleLayer(val) { if(val == 1) { document.getElementById('div1').style.display = 'block'; document.getElementById('div2').style.display = 'none'; document.getElementById('div3').style.display = 'none'; document.getElementById('div4').style.display = 'none'; } else if(val == 2) { document.getElementById('div1').style.display = 'none'; document.getElementById('div2').style.display = 'block'; document.getElementById('div3').style.display = 'none'; document.getElementById('div4').style.display = 'none'; } else if(val == 3) { document.getElementById('div1').style.display = 'none'; document.getElementById('div2').style.display = 'none'; document.getElementById('div3').style.display = 'block'; document.getElementById('div4').style.display = 'none'; } else if(val == 4) { document.getElementById('div1').style.display = 'none'; document.getElementById('div2').style.display = 'none'; document.getElementById('div3').style.display = 'none'; document.getElementById('div4').style.display = 'block'; } } Hi all, I hope that someone can help me with this strange problem I have here. I have some script which changes a button and changes the onclick event. The strange thing is that although it is changing it. All the events have the same parameter even though my code is giving each button's onclick event it's own unique parameter. Here's my Code. Code: var AllocPeople = window.opener.document.getElementById('AllocPeople'); if(AllocPeople.value.length > 0) { var people = AllocPeople.value.split(","); var Controls = new Array(); for(var P in people) { var id = people[P]; Controls[P] = document.getElementById('bt_AP_'+id); Controls[P].innerHTML = "Deallocate"; Controls[P].onclick = function() {Remove_Player(id)}; } } Thanking you all in advance. Hi, I am fairly new to this. I am looking to add an onclick value to open a new url when a particular airport (see code below) is selected. Where would each onclick value be placed and what should it look like? I have tried adding onclick values but to no avail! Any help would be greatly appreciated. The code I have (which can probably be improved upon) is the following: PHP Code: <div class="sign" style="margin-bottom:5px;"> <div class="boxTopSepLeft"><div class="boxTopSepRight"></div></div> <div class="boxContentLeft"><div class="boxContentRight"> <form method="GET" name="SelForm" class="alttxt" onsubmit="return check_form();" action="/cgi-bin/searching.pl?" > <input name="px" type="hidden" value="2" /> <input name="agent" type="hidden" value="100615" /> <input name="tmp" type="hidden" value="100615" /> <input name="tc" type="hidden" value="g" /> <input name="session" type="hidden" value="4f2f40bab764b3cccb97cc961dadf6ea" /> <table width="350" border="0" align="center" cellpadding="3" cellspacing="6"> <tr> <td width="85"><b class="quoteBoxTitles">UK Airport:</b></td> <td width="275" colspan="2"><select size="1" name="ap" class="quoteFormBoxes"> <option value="" selected>Select U.K. Airport</option> <option value="ABZ">Aberdeen</option> <option value="BFS">Belfast</option> <option value="BHX">Birmingham</option> <option value="BRS">Bristol</option> <option value="CWL">Cardiff, Wales</option> <!--option value="DOV">Dover</option--> <option value="DSA">Doncaster (Robin Hood)</option> <option value="MME">Durham Tees Valley</option> <option value="EMA">East Midlands</option> <option value="EDI">Edinburgh</option> <option value="EXT">Exeter</option> <option value="LGW">Gatwick</option> <option value="GLA">Glasgow</option> <option value="LHR">Heathrow</option> <option value="HUY">Humberside</option> <option value="LBA">Leeds/Bradford</option> <option value="LPL">Liverpool</option> <!--option value="LON">London</option--> <option value="LTN">Luton</option> <option value="MAN">Manchester</option> <option value="NCL">Newcastle</option> <option value="PIK">Prestwick</option> <option value="DSA">Sheffield (Robin Hood)</option> <option value="SOU">Southampton</option> <option value="STN">Stansted</option> <option value="MME">Teesside</option> </select> </td> </tr> <tr> I keep getting 28 when I am suppose to get 22 because of Order of Operations. Code: <html> <head> <title>Movie</title> <script type="text/javascript"> function ticketOrder() { var cost; var ticket; if(document.movieTicket.radTicket[0].checked) { ticket=document.movieTicket.radTicket[0].value; ticket=parseInt(ticket); cost=cost*ticket; } if(document.movieTicket.radTicket[1].checked) { ticket=document.movieTicket.radTicket[1].value; ticket=parseInt(ticket); cost=cost*ticket; } if(document.movieTicket.radReward[0].checked) { cost=document.movieTicket.radReward[0].value; cost=parseInt(cost); } else if(document.movieTicket.radReward[1].checked) { cost=document.movieTicket.radReward[1].value; cost=parseInt(cost); } if(document.movieTicket.chkPopcorn.checked) { var popcorn=document.movieTicket.chkPopcorn.value; popcorn=parseInt(popcorn); cost=cost+popcorn; } if(document.movieTicket.chkSoda.checked) { var soda=document.movieTicket.chkSoda.value; soda=parseInt(soda); cost=cost+soda; } if(document.movieTicket.chkCandy.checked) { var candy=document.movieTicket.chkCandy.value; candy=parseInt(candy); cost=cost+candy; } alert(cost*ticket); } </script> </head> <body> <div id="Header"> <h2>The Chicago Movie Palace</h2> </div> <form name="movieTicket"> How many tickets would you like to order?<br /> 1 Ticket<input type="radio" name="radTicket" value="1" /><br /> 2 Tickets<input type="radio" name="radTicket" value="2" /><br /> 3 Tickets<input type="radio" name="radTicket" value="3" /><br /> 4 Tickets<input type="radio" name="radTicket" value="4" /><br /> 5 Tickets<input type="radio" name="radTicket" value="5" /><br /> Are you a member of our theater?<br /> Yes<input type="radio" name="radReward" value="8" /><br /> No<input type="radio" name="radReward" value="10" /><br /> Would you like any food or drinks with your movie?<br /> Popcorn ($4)<input type="checkbox" name="chkPopcorn" value="4" /><br /> Soda ($3)<input type="checkbox" name="chkSoda" value="3" /><br /> Candy ($3)<input type="checkbox" name="chkCandy" value="3" /><br /> Which movie would you like to see? <select name="selUpcomingMovie"> <option value="Immortals">Immortals</option> <option value="J Edgar">J Edgar</option> <option value="Sherlock Holmes:A Game of Shadows" >Sherlock Holmes:A Game of Shadows</option> </select> <p><input type="button" name="btnSubmit" value="Order Tickets" onclick="ticketOrder()" /></p> </form> </body> </html> Hi all, I'm a beginner in JavaScript can someone please help me to resolve this issue and thanks in advance for your help! What I'm trying to do is.. When you select multiple <div> get the value of each one and save in separate hidden fields accordingly. What needs to happen is... Click div 1 --> if hidden field1 value is "none", save there, else check hidden field 2 if that's "none" save in hidden field 2 Click div 2 --> if hidden field1 value is "none", save there, else check hidden field 2 if that's "none" save in hidden field 2 Here's what I've come up with so far (currently I'm using JQuery) The problem with this is that no matter what div I click in which order it only updates the 1st hidden field Code: <div id="click1" name="click1" value="123" onclick="abc()"/>Click 1</div> <div id="click2" name="click2" value="225" onclick="def()"/>Click 2</div> <input id="passenger_1" name="passenger_1" type="hidden" value="none" /> <input id="passenger_2" name="passenger_2" type="hidden" value="none" /> <script> function abc() { var pasvalue = $('#click1').attr('value'); var pas1_value = $('#passenger_1').attr('value'); var pas2_value = $('#passenger_2').attr('value'); if(pas1_value == "none"){ $('#passenger_1').attr('value', pasvalue); }else if (pas2_value == "none"){ $('#passenger_2').attr('value', pasvalue); }} function def() { var pasvalue = $('#click2').attr('value'); var pas1_value = $('#passenger_1').attr('value'); var pas2_value = $('#passenger_2').attr('value'); if(pas1_value == "none"){ $('#passenger_1').attr('value', pasvalue); }else if (pas2_value == "none"){ $('#passenger_2').attr('value', pasvalue); }} </script> i have this frameset: http://www.mediafire.com/?75dvswgvelw19a9 this is somehow the like my other posts but im dealing with the radio buttons. what i want is when i click on the "create" button in form1 http://www.mediafire.com/?eld7a1rb21h799e it will pass the value to form 2 http://www.mediafire.com/?f0o060cdpyf06ya. so when i select "yes" in form1 and click on "create" it will autoselect "On" in form2. if i select "no" in form1 and click on "create" it will autoselect "off" in form2. Hello, I am trying to use the onclick function to allow a user to change the color of a photo. Everything works but I need a more practical way than using a bunch of IF statements. Here is what I have so far. This is just the function part I can include it all if needed. Code: function changeImage(c_img) { if(c_img == "cameo") { document.images("changingImage").src = "content/Image/Cameo.jpg"; } else { document.images("changingImage").src = "content/Image/GreenChili.jpg"; } Now I need to add 12 more imgs to this. It works if I throw 12 more if(c_img...)but there must be a better way. I am kinda a newbie when it comes to Java.. Thanks for any advice. I've got a table in which I want to have certain elements changeable if the user presses a button. The elements are stored in an array and I want to cycle through them when the button is pressed. Here's a section of what I'm working with so far: Code: <tr> <td valign="top"> <dl> <script type="text/javascript"> var w=0; var s=0; var c=0; var slugga_replace_list = new Array("Slugga","Shoota","Shoota/Rokkit","Shoota/Skorcha","Twin-Linked Shoota"); var choppa_replace_list = new Array("Choppa","Big Choppa","Power Klaw"); var warboss_wargear = new Array(); warboss_wargear[0] = slugga_replace_list[s]; warboss_wargear[1] = choppa_replace_list[c]; warboss_wargear[2] = "Stikkbombz"; for (w=0; w<2; w++) { document.write("<dt><input type='button' name='subtract' value='-' onclick='subtract()'>"+warboss_wargear[w]+"<input type='button' name='add' value='+' onclick='add()'/></dt>"); } function add() { s++ return s; } function subtract() { s-- return s; } </script> </dl> </td> </tr> I've tried using the ++ and -- to change the value of s, but it's not changing the text. Am I in the neighborhood at least? hi, i currently have an array of 20 images. on load a random selection of 15 are taken, then they ordered randomly on the page and doubled (to play a match the pairs memory game) clicking restart will reorder the images randomly, but will use the same 15 chosen on page load. i need the restart button to choose another random 15 images from the 20 in the array. here is the site: http://www.thebigappwall.com/test.htm and here is the code: Code: // Concentration Memory Game with Images - Head Script // copyright Stephen Chapman, 28th February 2006, 24th December 2009 // you may copy this script provided that you retain the copyright notice function randomOrd(){return (Math.round(Math.random())-0.5); } var back = '/images/back.png'; var tile = ['/images/lij.png','/images/myh_appwall.png','/images/Tap-Forms-icon-40.png','/images/urban-rivals-app-40.png','/images/warshipicon.png','/images/www2pdf-40.png', '/images/pandora.png','/images/preschoolicon.png','/images/my_virtual_girlfriend_40x40_01.jpg','/images/my_virtual_girlfriend_40x40_02.jpg','/images/my_virtual_girlfriend_40x40_03.jpg','/images/my_virtual_girlfriend_40x40_04.jpg','/images/www2pdf-40.png','/images/preschoolicon.png','/images/pandora.png','/images/blank32.png','/images/blank32.png','/images/blank32.png','/images/blank32.png','/images/blank32.png','/images/blank32.png','/images/blank32.png','/images/blank32.png','/images/blank32.png']; tile.sort( randomOrd ); function randOrd(a, b){return (Math.round(Math.random())-0.5);} var im = []; for (var i = 0; i < 15; i++) {im[i] = new Image(); im[i].src = tile[i]; tile[i] = '<img src="'+tile[i]+'" width="40" height="40" alt="tile" \/>'; tile[i+15] = tile[i];} function displayBack(i) {document.getElementById('t'+i).innerHTML = '<div onclick="disp('+i+');return false;"><img src="'+back+'" width="40" height="40" onclick="addClick();" alt="back" \/><\/div>';} var ch1, ch2, tmr, tno, tid, cid, cnt; window.onload=start; function start() {for (var i = 0; i <= 29 ;i++) displayBack(i);clearInterval(tid);tmr = tno = cnt = 0;tile.sort( randOrd );cntr(); tid = setInterval('cntr()', 1000);} function cntr() {var min = Math.floor(tmr/60);var sec = tmr%60;document.getElementById('c-timer').innerHTML = min+':'+ (sec<10 ? '0' : '') + sec;tmr++;} function disp(sel) {if (tno>1) {clearTimeout(cid); conceal();}document.getElementById('t'+sel).innerHTML = tile[sel];if (tno==0) ch1 = sel;else {ch2 = sel; cid = setTimeout('conceal()', 900);}tno++;} function conceal() {tno = 0; if (tile[ch1] != tile[ch2]) {displayBack(ch1);displayBack(ch2);} else cnt++; if (cnt >= 15) clearInterval(tid); } Thanks Hey all! So there I was newly hired and tasked with pouring through someone else's code to see what could be modified and brought up to date. After successfully finding the errors and correcting them and fulfilling the tasks my new supervisor assigned me, he slaps me on the back and says, "Well done! Now make it dynamic!" By which he meant the chapter buttons I spent hours creating from the existing code. Here's what he wants: the old code has an array, we'll call it someArray, that is assigned its values by the instructional developer as html pages are added to the course. So for example the code might look like this, Code: var someArray = new Array(4); someArray[0] = "video1/video1.html"; someArray[1] = "video2/video2.html"; someArray[2] = "video3/video3.html"; Now, each page has an associated chapter button. So video1/video1.html would have ch1Btn, video2/video2.html would have ch2Btn and so forth. Each button in turn calls a specific function which does only one thing - sets the currentPage variable to page associated with that button/array contents. For example, I have created the following functions to call each page: Code: function doCh1(){currentPage = 0; goToPage();} function doCh2(){currentPage = 1; goToPage();} function doCh3(){currentPage = 2; goToPage();} I should mention that all this is being done from within an html wrapper that calls each page into an iframe. The currentPage variable is assigned the url of one of the elements from the pageArray. My supervisor wants to be able to manually add pages to the pageArray and have the javascript code generate the associated buttons and function calls so when the learner clicks on one of the dynamically created buttons, s/he is taken to the correct page. Currently I'm using static images with the onclick calling the correct function to set my currentPage value and send the learner on his/her merry way. Is there a way to do all of this dynamically? If so, can you help me get my head around this by providing some examples? Sorry for the long post. Thank you, M Hi.. I should warn, i know almost nothing about javascript. . i've been trying read sample scripts and examples on how to modify this script; but I just don't know enough. I have a script that pulls data from an array, and copies it directly to the clipboard when a user clicks on it. The problem is this only works in IE, because Firefox doesn't by default allow that to happen. I'm trying to change it so that when it is clicked, instead, it takes what was going to be copied to the clipboard, and puts it in a Prompt box for the user to copy and paste. I had other scripts that do that, but I can't for the life of me figure out how to learn from it! This is the function in the current script Code: <script language="javascript" type="text/javascript"> <!-- function selectThis(src) { document.selection.clear; txt = eval(src +".innerText"); theObj = document.all(txt); txtRange = document.body.createTextRange(); txtRange.moveToElementText(eval(src)); txtRange.select(); txtRange.execCommand("RemoveFormat"); txtRange.execCommand("Copy"); alert(txt + " '.$caption[ 'paste' ].'"); } --> </script> '; } and this is the onclick code Code: '; foreach ( $ausgabe as $key => $data) { if ( $key == '' ) continue; if ( ( $_GET[ 'group' ] != '*' ) && ( $this->info[ $key ][ 'xx_data' ] != $_GET[ 'group' ] ) ) continue; $tpack = $this->info[ $key ][ 'pack' ]; $tname = $this->info[ $key ][ 'xx_desc' ]; $jsid= $nick2.'_'.$tpack; if ( isset( $this->info[ $key ][ 'xx_lock' ] ) ) { if ( $this->hide_locked > 0 ) continue; $tname .= ' (gesperrt)'; } $tname = htmlspecialchars( $tname); if ( $javascript > 0 ) { $tname = '<span class="selectable" onclick="javascript:selectThis(\''. $jsid.'\');">'. $tname."</span>\n". '<span id="'.$jsid.'" class="hidden">'. '/msg '.$this->nick.' xdcc send '.$tpack."</span>\n"; } if ( isset( $this->info[ $key ][ 'xx_note' ] ) ) $tname .= '<br>'.$this->info[ $key ][ 'xx_note' ]; $label = "Download mit:\n/msg ".$this->nick.' xdcc send '.$tpack."\n"; if ( isset( $this->info[ $key ][ 'xx_md5' ] ) ) $label .= " \nmd5: ".$this->info[ $key ][ 'xx_md5' ]; if ( isset( $this->info[ $key ][ 'xx_crc' ] ) ) $label .= " \ncrc32: ".$this->info[ $key ][ 'xx_crc' ]; echo ' <tr> <td class="right">#'.$tpack.'</td> <td class="right">'.$this->info[ $key ][ 'xx_gets' ].'</td> <td class="right">'.makesize($this->info[ $key ][ 'size' ]).'</td> <td class="content" title="'.$label.'">'.$tname.'</td> </tr> '; I've spent days at trying to customize it.. but.. i'm not a programmer I was able to get it to open a prompt box, and had it populate with ("copy this code", $variable), but cannot figure out how to have it display the proper values that was clicked on. I have no idea though what is considered efficient either in the code. I hope this isn't considered asking for TOO much help.... Within my project, using PHP/HTML/Javascript, I am trying to set up a page where a corresponding submit button is enabled when a given checkbox is checked. What complicates my attempt is that the checkboxes and submit buttons are in the form of arrays. Here is a snippet of my code: Code: <form name="myform4" id="list_apps" method="post"> <?php for ($i=0; $i<$num_rows;$i++) { ?> <p> <input type="checkbox" name="app[]" id="app[]" onclick="enable_perm()"> <input name="set_perm[]" type="submit" id="set_perm[]" value="Set Permissions"> </p> <?php } </form> Here is my attempt at using Javascript to disable the first submit button after clicking any check box: Code: function enable_perm() { document.myform4.set_perm[0].disabled = true; } What am I missing here, or, how do I enable/disable submit buttons that are part of an array? THIS IS NOT HOMEWORK Hi all, Simple question: Is it "legal" to conditionally declare variables? For example: First Code: if (name) { var age = 54; var year = 1957; } Second Code: var age; var year; if (name) { age = 54; year = 1957; } Is "First" wrong and "Second" right? Or are they both equally OK? Thanks. -- Roger Edit: Please explain your answer. hello I am having a problem to add numbers store in an array. arrayValues[0][0] = 1; arrayValues[0][1] = 2; var col = 0; var sum; for ( var row = 0; row < index; i++ ) sum += arrayValues[col][row]; my result is ==> 12 it is defining my sum variable as string. even I try do do this var sum = 0; to define sum as numeric variable. my result was ==>012. Any idea, this is my first javaScritp code. Thanks. Hi Guys, How do I sum the values of an array and output the result using document.write? Say my array is var number=new Array(1.234,56.43,1.02); THANKS Thought this wud work? Code: <script type="text/javascript"> var x = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write(sum(x)); </script> |