JavaScript - Every Time I Click A Button I Need A Function To Run Once.
How can I do this? I'm new to JavaScript. I tried messing with While but it just caused lag as it kept looping infinitely.
The problem I think is that I have a variable that changes every time I click the button. The function changes the variable. So it successfully changes the variable once to my likings, then when I click the button (thus running the function) it does nothing. Here's an example I created to show you Quote: <html> <head> <script type="text/javascript"> var x = 50; var y = Math.floor(Math.random()*5); function test() { var a = x+y document.getElementById("testing").innerHTML=a; } </head> <body> <p id="testing"></p> <input type="button" value="asdf" onclick="test()" /> </body> </html> So in this case, I need to click the button multiple times in which each time it should add y to x. It only works once and then goes kaput. Thanks! Similar TutorialsHello I am new to javascript (4 months), I would like to add an hour to the current time each time a button is clicked. I have this code: ------------------------------------------------------------------ var hourstbutton=document.getElementById("button3"); hoursbutton.onclick=function() { var divlink=document.getElementById("math3"); var newtime2=new Date(); var currenthours2=newtime2.getHours()+1; var currentmins2=newtime2.getMinutes(); var currentsecns2=newtime2.getSeconds(); var ampm2= (currenthours2>=12) ? "P.M." : "A.M."; if (currenthours2>=13) { currenthours2-=12; } if(currenthours2<1){ currenthours2=12; } if(currentmins2<10){ currentmins2= "0" + currentmins2; } if(currentsecns2<10){ currentsecns2="0" + currentsecns2; } divlink.innerHTML=currenthours2+":"+currentmins2+":"+currentsecns2+ " "+ampm2; ------------------------------------------------------------------------ How do I tie the number of button clicks into the number of times this code is executed? Any help is appreciated thanks. Hi all, Background: I'm currently working on a landing page which will display the same on both desktop & mobile devices, which is what we "want" for now. However, we've created an alternate registration page for mobile devices. This page can be accessed by clicking on a specific button, which has a class on it that will determine if the user is on a mobile device or not. If they are not, the normal action will occur, such as a registration popup, built specifically for desktop users. The problem is: I'm firstly having to use .remove to take away the class of pbx_ajax which operates the popup, so mobile users aren't affected by the popup and will continue onto the page we specially built for them. However, it seems my script is removing the class straight away, which prevents the popup from working for desktop users. Secondly, the script doesn't actually seem to work, it simply doesn't fire, which begs the question if i've cocked up my class bind. Code is attached below, please if anyone has any advice, do let me know as i'm at my wits end. Oh and i'm sure you'll notice, i'm polling for when the jQuery has loaded, as the library is located at the bottom of our site (its a rather large site). The javascript/jquery Code: //$(document).ready(function() { //Global function that will detect what device the page is being viewed on function globalDetectDevice() { var deviceIphone = "iphone"; var deviceIpod = "ipod"; //Initialize our user agent string to lower case. var uagent = navigator.userAgent.toLowerCase(); //************************** // Detects if the current device is an iPhone or iPod Touch. function DetectDevice() { if (DetectIphone()) { window.location = "/landing/register/mobile" ; } else if (DetectIpod()) { window.location = "/landing/register/mobile" ; } else { return false; } } } //Binding the above function to a class, that we can then attach to any clickable element //As jQuery is at the bottom of page, we poll the function until jQuery has loaded, once loaded, we clear the polling using clearTimout var bindTimer = setInterval(function() { if ("undefined" != typeof jQuery && globalDetectDevice) { $('.detectDevice').removeClass('pbx_ajax').bind('click', DetectDevice); clearTimeout(bindTimer); } }, 50); //} the html button Code: <a class="detectDevice pbx_ajax" title="Join Free" href="?cat=popup&action=open&settings=pbx_popup_register">~graphic("btn-get-started-prints-LP")</a> thanks for any help First off, I apologize if I'm in the wrong area. I was referred to the site here by a neighbor of mine that has used these forums in the past. Before I move forward with finding someone to help me with some kind of a browser extension, I need to know if it is even possible to do. I have zero experience with anything code related, but wanted to do a little leg work here. The basic goal is to be able to input a specific time of day, and have the code execute a click on a button or link. The more specific the timing can be, the better. I've done a little research over the past couple evenings, and I see that there are ways to use time intervals. I would if possible like to use exact hour, minutes, seconds, and even milliseconds. Alternatively, if anyone has come across something that already does what I'm looking for. I would be much appreciative if you could point me in that direction. Thank you all for your time. i'm still a relative noob and this has me stuck - i have a save button with a "save as copy" in the save dropdown list. add new item directs to a premade/formatted project that is used as a template, so on that item i only want/need the "save as copy" but on all other items that use the form i need to only have the "save" function. is there any way to either change the function of the button depending on item that is being viewed in the edit screen OR hide the "save" button and only show the button associated with "save as copy - and vis versa for the rest of the items?? current button code is - protected function getToolbar() { $options = array(); $user = JFactory::getUser(); $create_ms = $user->authorise('core.create', 'com_pfmilestones'); $create_task = $user->authorise('core.create', 'com_pftasks'); $options[] = array( 'text' => 'JSAVE', 'task' => $this->getName() . '.save'); $options[] = array( 'text' => 'Save as new project', 'task' => $this->getName() . '.save2copy', 'options' => array('access' => ($this->item->id > 0))); PFToolbar::dropdownButton($options, array('icon' => 'icon-white icon-ok')); item used as template is id=8 any help or suggestions would be greatly appreciated.. Hi, I am not entirely sure what I am doing wrong here, and I have been looking at this for ages, so apologies in advance if I have become so bleary eyed I can't see something simple. I use php to create buttons based on values pulled for a table. The problem I have is when you click on the first button the javascript function works great, when you click on the next button you get the same output even though it should be different results. I am working in ff and I can see on my firebug console that the javascript function is being called, but it is not passing the new value of the second or third button, it just keeps repassing the value of the first button. So not entirely sure where I am going wrong here. My page is: Code: <script type="text/javascript"> function loadXMLDoc2(File,ID,Msg){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } var params=Msg; xmlhttp.open("POST",File,true); xmlhttp.setRequestHeader("Pragma", "Cache-Control:no-cache"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", params.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.send(params); } </script> <head> <body> <?php $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mydb", $con); $result = mysql_query("SELECT DISTINCT theme FROM goods WHERE category='{$_POST['category']}' ORDER BY theme DESC"); while($row = mysql_fetch_array($result)){ echo '<input type="text" class="hidden" name="theme" id="theme" value="' . $row['theme'] . '" ><input type="button" class="button3" name="product" id="product" value="' . $row['product'] . '" onClick="loadXMLDoc2(\'getShow.php\',\'txtHint\',\'theme=\'+encodeURI(document.getElementById(\'rtheme\').value))" > '; } echo '<br /><br /> <div id="txtHint"><div> <br /> <br />'; mysql_close($con); ?> And getShow.php produces a table with a list of product images, names and prices, based on theme. So basically not sure where I am going wrong here? Hello, I am working on a tool for hardware quoting, I'm currently trying to add a button for adding line items to the quote. Here is what I currently have: The HTML: Code: <html> ... <input type="button" id="sbutt" onclick="buttinc()" value="Click Me" /> <div id="txtarea"></div> ... </html> The script: Code: vbutt = 0 function buttinc() { var buttona = document.getElementById("txtarea"); if (vbutt<100) { buttona.innerHTML="<div id='newdiv" + vbutt + "'></div><br />"; var buttb = document.getElementById("newdiv"+vbutt); buttb.innerHTML = "some text" + vbutt + "close tags and stuff"; vbutt = vbutt + 1; } } Now, it is sort of working the way I expect. When the button is clicked, it creates the new div, starts the id at 0, and increments the div id each time the button is pressed afterwards. It also displays the text (buttb.innerHTML) in the new div. However, it only increments the id of the same div, it doesn't create a new div under the first one. What I am hoping for is: click 1 : <div id="newdiv0">0</div> click 2 : <div id="newdiv1">1</div> click 3 : <div id="newdiv2">2</div> etc What it is doing: click 1 : <div id="newdiv0">0</div> click 2 : <div id="newdiv1">1</div> (newdiv0 disappears) click 3 : <div id="newdiv2">2</div> (newdiv1 disappears) What am I missing? Any help is appreciated. hye.. i'm trying to calculate value of balance by substract cash to total. But nothing happen. here is my code: Code: <script type="text/javascript"> function substract(){ { document.calculate.Cash.value = ZA; document.calculate.Total.value = Z1; balance(); } function balance(){ AAA = document.calculate.Balance; AAA.value = (ZA-Z1).toFixed(2); } </script> </head> <body style="background-color: #99FF99"> <?php // if there are any errors, display them if ($error != 'Unable to update') { echo '<div style="padding:12px; border:1px solid purple; color:red; font-weight: bold; text-align: center; font-size: medium; ">'.$error.'</div>'; } ?> <form action="" method="post" name="calculate" style="width: 1320px; "> <div class="style1"> <input type="hidden" name="CustID" value="<?php echo $CustID; ?>"> <input type="hidden" name="Total" value="<?php echo $Total; ?>"> <input type="hidden" name="TableID" value="<?php echo $TableID; ?>"> <div class="style5" style="width: 820px; height: 148px; margin-left: auto; margin-right: auto;"> <p class="style9"> </p> <p class="style17"><span class="style19">CUSTOMER </span> <strong> <span class="style19">ID:</span></strong> <strong> <?php echo $CustID; ?> </strong></p> <table style="width: 35%; height: 185px; margin-left: auto; margin-right: auto;" class="style15"> <tr> <td class="style11" style="width: 111px; height: 30px;"><strong>Table ID : </strong></td> <td style="height: 30px; width: 169px;" class="style18"><strong><?php echo $TableID; ?></strong></td> </tr> <tr> <td class="style1" style="width: 111px; height: 20px;"></td> <td style="height: 20px; width: 169px;" class="style1"></td> </tr> <tr> <td class="style16" style="width: 111px; height: 30px;"><strong>Total : </strong></td> <td style="height: 30px; width: 169px;" class="style18"><strong> RM<?php echo $Total; ?> </strong></td> </tr> <tr> <td class="style1" style="width: 111px; height: 20px;"></td> <td style="height: 20px; width: 169px;" class="style1"></td> </tr> <tr> <td class="style16" style="width: 111px; height: 30px;"><strong>Cash : </strong></td> <td style="height: 30px; width: 169px;" class="style1"> <strong> <span class="style20">RM</span> <input type="text" name="Cash" id="Cash" class="style17" style="width: 120px"></strong></td> </tr> <tr> <td class="style1" style="width: 111px; height: 20px;"></td> <td style="height: 20px; width: 169px;" class="style1"></td> </tr> <tr> <td class="style16" style="width: 111px; "><strong>Balance : </strong></td> <td style="width: 169px;" class="style1"><strong> <span class="style20">RM</span> <input type="text" name="Balance" id="Balance" value="0.00" class="style17" style="width: 120px"></strong></td> </tr> </table> <p class="style5"><strong> <input class="style3" name="calculate" type="button" onclick="substract()" value="Calculate"> <input class="style3" name="submit" type="submit" value="Done"></strong> </div> </div> </form> Hi. 1) I would like to click the Download button on this site, then wait lets say 60 sec & click free download button. http://uploading.com/files/S4WYPP73/...r_ENG.rar.html I remember that somehow it is possible to create the Request URL & then input it into IE & the server will think I hit the button. But how can I make the URL? And how is it called? posting URL request? I will be using firefox or I can make HTML file & execute it in IE for every file. PHP Code: <form action="http://uploading.com/files/get/S4WYPP73/" method="post" id="downloadform"> <input type="hidden" name="action" value="second_page" /> <input type="hidden" name="file_id" value="4663720" /> PHP Code: function do_step_1() { do_request('files', 'get', {file_id: 4663720, action: 'step_1'}, function(wait_time){ if(wait_time > 0) start_timer(wait_time); else if(wait_time <= 0) download(); }); } function do_step_2() { do_request('files', 'get', {file_id: 4663720, action: 'step_2'}); } PHP Code: function download() { $('#waitblock').html('Free Download'); $('#waitblock').click(function(){ do_step_2(); }); } Hey I want to enforce a click on the facebook share button, please help me out here. I was thinking something like this: Code: javascript:window.location="http://www.facebook.com/connect/prompt_feed.php?locale=en_US&message=hi"; javascript:function selectFirst() { publish.focus(); publish.click();} selectFirst(); Something wrong with that code? What code would work? Is it not possible? Thanks a lot, Sarah I would like for the script to say "Ok here is the button on this page *clicks* (or submit)" I have tried this with out help, I'm not really sure what to do. I've tried learning what I can on my own, I've tried using the search tool. Here is the part of the code I am trying to use to make my click button. Code: <div id="interactiveBox"> <div class="divpad3"> <form name="buyform" method="POST" action="/marketplace/userstore/2690240/buy/?id=567595175&step=submit" ENCTYPE="application/x-www-form-urlencoded"> <strong>Buy It Now</strong> <strong>Password</strong> <input type="password" class="marketplaceInputField" name="password"> <input type="hidden" name="nonce" value="860307364.1283901229.441212630"> <button type="submit" class="cta-button-sm"><span>Buy Now</span></button> <br /><br /> </form> Here is what I have tried and failed.. This code will be used in combination with greasemonkey Code: <script>function clickOnLoad() { document.buyform.submit.value = "true"; } body onload="clickOnLoad()"</script> Hi there. I want to alert the user that he or she has not clicked on any of the radio buttons in each group. How do I do so? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type="text/javascript"> function validateRadio(obj,correct){ var result = 0 for(var i=0; i<obj.length; i++){ if(obj[i].checked==true && obj[i].value==correct) result = 1 } if(!result && obj.value == correct) result = 1 return result; } </script> </head> <body> <form onsubmit=" var err = '' if(!validateRadio(this.a,3 || 1)) { err+='\nFirst radio is wrong'; } if(!validateRadio(this.b,2 || 1)) { err+='\nSecond radio is wrong'; } if(err.length) { alert('Problem:'+err); return false; } else { alert('Good Job -- Submitting'); return true; }" action="#"> Choose "3" <input type="radio" name="a" value="1" /> 1 <input type="radio" name="a" value="3" /> 3 <p>Choose "2" <input type="radio" name="b" value="1" /> 1 <input type="radio" name="b" value="2" /> 2 </p><p><input type="submit" value="Submit" /> </p></form> </body> </html> Please advise. I want to show an hourglass instead of a mouse pointer on click of a button. I'm having both client and server side validations on the button click event. I have written the code for hourglass in the javascript function along with the validations. Now, on click of the button the hourglass gets displayed after 3-4 seconds and not immediately. According to me, the hourglass is getting displayed after the javascript function(client side validation) is executed and before server side validation begins. Is there any way to display the hourglass without delays ? Kindly let me know if there is any fix for eliminating this delay. I hope my question is clear. Please let me know if i'm wrong somewhere as i'm new to javascript programming. Thanks in advance. zizou. Hi guys, At the moment i have this code which disable the middle button in Safari and Chrome.. Code: $('body').mousedown(function(e){ if(e.button==1) return false } ); How can I disable it in Firefox and IE?.. i think IE middle button ==4 but its not working for me. Thanks in advance! I dont get why that doesn't work... it has me baffled 0.o Code: <html> <div id="divId">Button clicked 0 times</div> <input type="button" value="click me" onclick="divClick()" /> <script type="text/javascript"> var i = 0; function divClick() { var colorNum1 = Math.floor(Math.random()*255); var colorNum2 = Math.floor(Math.random()*255); var colorNum3 = Math.floor(Math.random()*255); var color = "rbg(" + colorNum1 + "," + colorNum2 + "," + colorNum3 + ")"; i++; var divId = document.getElementById("divId"); divId.style.backgroundColor = color; divId.innerHTML = "Button clicked " + i + " times"; } </script> </html> figured it out finally i had rbg instead of rgb >< hi to all, sorry for this question. First I have to say this that I'm very noob in javascript. My question is how to show the value of my radio button when click. I have this code: Code: <tr><td width="10px"></td><td width="60%">Neatness</td> <td width="40%"> <input name="neat" type="radio" class="hover-star" value="1" title="Poor"/> <input name="neat" type="radio" class="hover-star" value="2" title="Fair"/> <input name="neat" type="radio" class="hover-star" value="3" title="Satisfactory"/> <input name="neat" type="radio" class="hover-star" value="4" title="Outstanding"/> </td></tr> say when my 1st radio button it will show 1 or so on.. How can I achieve this? Or better yet does anyone know hot to do this in jquery. I have a script which creates an element of iframe. I have a button which refreshes the iframe link. I need to do something to change a variable in the iframe src on every click of the button. I'll explain the real issue. I have a list of games I have with random name like, boomer.swf, kingdom.swf, balloon.swf and so on. So I somehow made this, Code: var r_text = new Array (); r_text[0] = "boomer"; r_text[1] = "kingdom"; r_text[2] = "balloon"; var i = Math.floor(3*Math.random()) var gamedrome = { game: ""+r_text[i]+""}; Now I have a .js file which creates iframe element Code: function embed_game(params, options) { var data = []; for(var i in params) { data.push(i + "=" + encodeURIComponent(params[i])); } data = data.join("&"); var frame = document.createElement("iframe"); frame.src = "http://website.com/embed/game.html?"+ data; frame.style.width="100%"; frame.style.height="100%"; frame.style.border = "0"; frame.frameBorder = "0"; frame.id="newroom"; .... and another small script to refresh the inner iframe and not the page to change game. Code: <script type="text/javascript"> function Reload () { var f = document.getElementById('newroom'); f.src = f.src; } </script> It all works fine until the game is loaded, but the problem is that if once the game is loaded in site, the iframe source is already set and my button keeps loading the same game. I need to randomize it on every click. Please help me out. I want to change the color of the gridview when a button which has the value of the row index of the gridview is clicked ...this button is not inside the gridview but some where else on the form but it can send the gridview rowindex to the function so need a function to change the color of the row or bring it to focus in someway... this is my code ______________________________________________________________ <pega:when test="$mode-input"> <script language="JavaScript"> function showNextButton() { handleClientEvent('SERVER','MakeScoreOrder','','-1'); /* fetches the data */ var submitClicked = "<p:r n='pyWorkPage.PFRSData.SubmitClicked' />"; var submitClicked = submitClicked.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); var msg = "<p:r n='pyWorkPage.PFRSData.HasMessages' />"; var msg = msg.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); if (submitClicked == "" || msg =="true") { toggleSubmitBtn(0); } else if (submitClicked == "true" || msg =="false") { toggleSubmitBtn(1); } } function toggleSubmitBtn(status) { var submitButton=document.actionForm.submitButton; if(submitButton) { var parentTable=pega.u.d.findParentTable(submitButton); if(parentTable) if(status) { if(parentTable.style.display=='none' || parentTable.style.display=='') { parentTable.style.display='inline'; document.actionForm.submitButton.disabled=false; } } else { parentTable.style.display='none'; document.actionForm.submitButton.disabled=true; } } } </script> <button onClick="showNextButton();" id="PISSubmit" style="vertical-align:middle;"> <span class='buttonLeft'></span> <span class='buttonMiddle'> <span class='buttonText' onmouseover="this.className='buttonTextHover'" onmouseout="this.className='buttonText'">Submit</span> </span> <span class='buttonRight'></span> </button> </pega:when> ___________________________________________________________ On clicking PISsubmit button it should fetch data and display the next button(submitButton).. but on first click nothing happens on second click it fetches the data and third click it displays Next(submitButton)button. Kindly help !! Note: its in pega application. I have these buttons that I need to have switch accounts on and off. They work, but for some reason the words on the buttons are not changing from Activate to Deactivate... It seems as though the button is not updating itself after success of the function. First post on here so I apologize if I am doing this wrong. Problem code in jsbin--> http://jsbin.com/okifa3/ Code: $(function() { var activateOwner = function(u) { var dataString = 'oid=' + u + "&a=1"; $.ajax({ type: "GET", url: "{/literal}{$site_root_path}{literal}account/toggle-owneractive.php", data: dataString, success: function() { $('#spanowneractivation' + u).css('display', 'none'); $('#message1' + u).html("Activated!").hide().fadeIn(1500, function() { $('#message1' + u); }); $('#spanownernamelink' + u).css('display', 'inline'); $('#' + u).val('Deactivate'); $('#spanownernametext' + u).css('display', 'none'); $('#' + u).removeClass('btnActivate'); $('#' + u).addClass('btnDectivate'); setTimeout(function() { $('#message1' + u).css('display', 'none'); $('#spanowneractivation' + u).hide().fadeIn(1500); }, 2000 ); } }); return false; }; var deactivateOwner = function(u) { var dataString = 'oid=' + u + "&a=0"; $.ajax({ type: "GET", url: "{/literal}{$site_root_path}{literal}account/toggle-owneractive.php", data: dataString, success: function() { $('#spanowneractivation' + u).css('display', 'none'); $('#message1' + u).html("Deactivated!").hide().fadeIn(1500, function() { $('#message1' + u); }); $('#spanownernamelink' + u).css('display', 'none'); $('#spanownernametext' + u).css('display', 'inline'); $('#' + u).val = 'Activate'; $('#' + u).removeClass('btnDeactivate'); $('#' + u).addClass('btnActivate'); setTimeout(function() { $('#message1' + u).css('display', 'none'); $('#spanowneractivation' + u).hide().fadeIn(1500); }, 2000 ); } }); return false; }; $(".toggleOwnerButton").click(function() { if($(this).val() == 'Activate') { activateOwner($(this).attr("id")); } else { deactivateOwner($(this).attr("id")); } }); }); |