JavaScript - Adding Javascript To A Form - An 'add To Cart' Button
Good morning! Hopefully somebody can help me with this javascript question. (No knowledge of Google Anayltics needed for this.) I'm adding Google Analytics 'Event Tracking' javascript to a typical 'Add to Cart' button. The customer enters desired quantity in the text box and clicks the 'Add to Cart' button to order. I would like to use the Event Tracking javascript to record the button click - plus the Value entered in the text box - as one event. Here's the code for the form (the text box and 'Add to Cart' button code lines are bold):
Code: <form method="post" action="http://www.yoursite.com/mm5/merchant.mvc?"> <input type="hidden" name="Screen" value="BASK" /> <input type="hidden" name="Product_Code" value="yourproductcode" /> <input type="hidden" name="Action" value="ADPR" /> <label for="quantity">Quantity:</label> <input type="text" name="quantity" value="0" /> <input type="submit" value="Add To Cart" /> </form> I came up with this javascript for the Event Tracking (to be inserted somewhere above): Code: onClick="_gaq.push(['_trackEvent', 'OrderForms', 'AddToCart', 'yourproductcode', document.getElementByName('quantity').value]);" I'm wondering where I would enter this javacript code inside the form code to pick up both the button click - plus the quantity? You'll notice that I'm using 'getElementByName' to extract 'quantity' from the text box and record its 'value'. If I enter this javascript on the 'Add to Cart' line - right after "Add to Cart", would 'quantity' still get picked up upon button-click - since it's all on the same form? Or would it be a problem because 'quantity' is contained in a different <input> container? Thanks! Any help is greatly appreciated. IB Similar TutorialsHey guys. This is vague because I dont know what exactly to tell you but please reply with me so I can fix this. I want to add something to my forum. Specifically, I want to add a HTML and Picture button for when you go to reply. Like posting an article here, there are also these options (font, alignment, insert image) I do not know how to achieve this but shouldnt be too hard. Here are the two sources you will need to look through to help me fix the forum. http://neoweather.com/FWFORUM.JS http://static.websimages.com/JS/fw.js THANKS Site in question: www.yourvancouvermortgagebroker.ca/apply On the 3rd step of this form, I want to add a "SKIP" button that will send the user to the 5th step. No clue how to do this, as someone else helped me code. Thank You! Relevant code javascript file: Code: //step 3 $('#submit_third').click(function(){ //remove classes $('#third_step input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var fields = $('#third_step input[type=text]'); var error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='cemail' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(!error) { //update progress bar $('#progress_text').html('60% Complete'); $('#progress').css('width','204px'); //slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown(); } else return false; }); //step 4 $('#submit_fourth').click(function(){ //remove classes $('#fourth_step input').removeClass('error').removeClass('valid'); var fields = $('#fourth_step input[type=text]'); var error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<1 || value==field_values[$(this).attr('id')]) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(!error) { //update progress bar $('#progress_text').html('80% Complete'); $('#progress').css('width','272px'); //slide steps $('#fourth_step').slideUp(); $('#fifth_step').slideDown(); } }); // step 5 $('#submit_fifth').click(function(){ //remove classes $('#fifth_step input').removeClass('error').removeClass('valid'); I need to figure out the on page button code, what I need to add to the javascript file AND what I need to add in the CSS. (css is here) Thank you SO much to whoever can help. Hey guys. I want to add something to my forum. Specifically, I want to add a HTML and Picture button for when you go to reply. Like posting an article here, there are also these options (font, alignment, insert image) I do not know how to achieve this but shouldnt be too hard. Here are the two sources you will need to look through to help me fix the forum. http://neoweather.com/FWFORUM.JS http://static.websimages.com/JS/fw.js THANKS Good afternoon. I'm trying to make it so a 'radio button' in a 'form' will 'collapse' a Div that I have hidden. I'm using the JavaScript to control the collapse, and google's Jquery for the rest of it. here's the code. Code: <head> <script type="text/javascript" src="SpryAssets/collapse.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> animatedcollapse.addDiv('test', 'fade=1, group=test, speed=400') animatedcollapse.ontoggle=function($, divobj, state) { //fires each time a DIV is expanded/contracted //$: Access to Jquery //divobj: DOM reference to DIV being expanded/collapsed. Use "divobj.id" to get the ID. //state: "block" or "none", depending on the state. } animatedcollapse.init() </script> </head> and the body code... Code: <form action="myform.php" method="post"> <a id="collapsable" href="javascript:animatedcollapse.toggle('test')"> [+] Testing the Collapsability of this Scripting.</a> <div id="test" style="display:none;"> <h1> You can see that if you toggle the 'Image Display' Button. This will display Properly.</h1> </div> </form> You can find a completely working version (When not using Radio buttons and forms) located at My Toggle Works Here. Alternatively, you can find the NON working version, which is what I'm attempting to get to work, located at My Toggle Doesn't Work. you can see that in the version that doesn't work, if you hit the 'Radio button', it will collapse, and immediately uncollapse the Div, I don't get why it does this. Any help is greatly appreciated. Hi there, I guess my question is very novice but I have to ask it. I can find lots of "form applications" on internet. But anytime I check them I cannot see any "send" button help. I mean I know that when I click it, it wont send the informations to my e-mail page. Because they don't show where to insert my email address there, in the example. So how can we make a form work for us, how can we arrange it to send the informations to our e-mail address? Do we need to use a php file for it? if yes, how? Regards and Thanks in advance I am writing a script to add an item to card in Applescript. Usually some variant of this works with most shopping sites: do JavaScript "document.getElementById('addToCart').onclick()" in document 1 However, I am lost here. How would I "click" this one? a href="javascript:fnAddItemToCartWithAccessories('1218308267319','2074657')" onclick="s_objectID="javascript:fnAddItemToCartWithAccessories('1218308267319','2074657')_1";return this.s_oc?this.s_oc(e):true"> <img id="addtocart" border="0" alt="Add to Cart" src="http://images.bestbuy.com/BestBuy_US/en_US/images/global/buttons/btn_addtocart_pdp.gif"> http://www.bestbuy.com/site/LG+-+21....&skuId=2074657 I want to have a button in a form that only calls a Javascript function, but not refresh the page, how do I do this?
Hello all I created a form which has a lot of textboxes, checkboxes and select-lists which are getting filled up by the records from a database table. I am basically creating an edit screen for a record. No I want to check all these input elements using javascript validation. I want this to performed when a button "Archive" is pressed. My problem is this "Archive button" needs to be a submit button. This does run the javascript validation but after completing the validation it submits the form. I want that submission should be stopped when the validation is violated. how can I do this? What I want is a button which acts as a default button (triggers the onclick event when I press enter) but submits only if the form is valid. Hello guys my question has changed, i dont want to double post so here is my new question, I now have 3 arrays name price quantity totalPrices now i want to create a table that will hold them but it will be created when you click the shop cart button, this button will take you to a blank page with the table on it i would like something like this Toy name| Quantity | Price | Total price Toy1 | Quantity | Price | Total price of that toy Toy2 | Quantity | Price | Total price of that toy Toy3 | Quantity | Price | Total price of that toy ----- | -------- | ----- | Total price all together I have looked at many tutorials but i cant get any to work, all they do is draw nothing and i cant get it to work Right now this javascript shopping cart works to 1. charge shipping based on the item, 2. the destination country, 3. it combines shipping for a quantity over 1 of the SAME item. Each item has 2 different possible shipping charges. I am trying to get the javascript to check the shopping cart to see what item in the cart has the highest possible shipping charge, charge that amount to that item, and charge the lowest possible shipping charge on all other items in the cart. If item A is purchased alone shipping is $5.00. If purchased with item B, which costs $10.00 to ship alone, the $10.00 is charged for item B and only $3.00 for item A. Because item B had the higher shipping charge at a quantity of one. I have tried adding various things like me.items[current], item.shipping, me.shipping, this.shipping, shipping_Cost, and other things next to the second && in the part of the script that shows the country. I have also tried adding && if (me.whatever) and && if (item.whatever) and similar things at the beginning of the script next to if (this.country). I have found the parts of the script that pertain to cart items and to updating the shopping cart. Now I am stuck. The javascript is in 2 parts. One part goes in the item page, which I will post first. The second part goes in an external javascript file which I will post at the bottom. In between there is the part that shows the shopping cart. It isn't part of the javascript. Code: <script type="text/javascript" src="simpleCart.js"></script> <script type="text/javascript"> <!-- simpleCart.checkoutTo = PayPal; simpleCart.email = "my Paypal email address"; simpleCart.cartHeaders = ["Name" , "Price" , "Quantity" , "remove" ]; CartItem.prototype.shipping=function(){ // we are using a 'country' field to calculate the shipping, // so we first make sure the item has a country if(this.country){ if( this.country == 'United States' && this.quantity == '1'){ return this.quantity*5.00; } else if( this.country == 'United States' && this.quantity >= '2') { return this.quantity*3.00; } else if( this.country == 'Belgium' && this.quantity == '1') { return this.quantity*12.00; } else if( this.country == 'Belgium' && this.quantity >= '2') { return this.quantity*9.00; else { return this.quantity*0.00; } } else { // use a default of $0.00 per item if there is no 'country' field return this.quantity*0.00; } } // --></script> Code: <div style="display:block;"></div> <div>SHOPPING CART</div> <div class="cartHeaders"></div><br><br><br> <div class="simpleCart_items"></div> <div id="totals"> Item Total: <span class="simpleCart_total"></span><br>Shipping Total: <span class="simpleCart_shippingCost"></span><br>Tax: <span class="simpleCart_taxCost"></span><br>Final Total: <span class="simpleCart_finalTotal"></span> </div> <br><br><br><br> <br><br> <a href="javascript:;" class="simpleCart_empty">Empty Shopping Cart</a><br><br> <a href="javascript:;" class="simpleCart_checkout">Checkout Through Paypal</a> </div></div> separate javascript file is here http://simplecartjs.com/documentation.html Hi, I was trying to add some simple javascript (toggle visibility function of a div) to the FB 'like' button and 'Google +1' button. This to simply create some more visitor interactivity by showing a thank you message for doing so. I've tried by just adding 'onclick=' to the element that actually shows the button, with a <a href="#" onlcick="..."> --element--</a> manner, and with a <span> and a <div> element around it. Neither of them work. The toggle script is 100% correct (using it actively with <a href="javascript:void(0);" onclick="javascript:toggleVisibility('feedbackform')">feedback</a> ) Of course I made sure the div id had correct name and it is unique for the toggle function. Anybody got any ideas on how to go with this? JS: Code: function toggleVisibility(controlId) { if (document.getElementById) { // DOM3 = IE5, NS6 var control = document.getElementById(controlId); if(control.style.display == "") control.style.display = "none"; else control.style.display = ""; } else { if (document.layers) { // Netscape 4 if(document.controlId.display == "") document.controlId.display = "none"; else document.controlId.display = ""; } else { // IE 4 if(document.all.controlId.style.display == "") document.all.controlId.style.display = "none"; else document.all.controlId.style.display = ""; } } } I am trying to add a pulldown menu with a button to my website. I have successfully done this with a javascript I found online here to give credit: http://www.blazonry.com/javascript/js_menu.php I tried to modify the form so it will use an image file instead of the default button. To troubleshoot I took the relevant code and put into a seperate html file. This one is using the default code from the site referenced above. This is the page published online: http://www.keylimecomputerservice.com/test/default.html Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <SCRIPT LANGUAGE="JavaScript"><!-- function openURL() { // grab index number of the selected option selInd = document.theForm.aaa.selectedIndex; // get value of the selected option goURL = document.theForm.aaa.options[selInd].value; // redirect browser to the grabbed value (here a URL) top.location.href = goURL; } //--> </SCRIPT> </head> <body> <TABLE SPAN="3" BORDER=1 CELLSPACING=0 CELLPADDING=0 align="center" WIDTH="60%"> <TR> <TD WIDTH="33%"> <center><font color="black">Choose a connection</font></center><br> <form name="theForm"> <tt> <center> <select name="aaa" size="1"> <option selected value="#"> ---------- </option> <option value="/remote/connect1.exe">Connection 1</option> <option value="/remote/connect2.exe">Connection 2</option> <option value="/remote/connect3.exe">Connection 3</option> <option value="/remote/connect4.exe">Connection 4</option> <option value="/remote/connect5.exe">Connection 5</option> <option value="/remote/connect6.exe">Connection 6</option> <option value="/remote/connect7.exe">Connection 7</option> <option value="/remote/connect8.exe">Connection 8</option> </select> </center> </TD> <TD WIDTH="33%"> <input type="button" value=" GO " onClick="openURL()"> </tt> </form> </TD> <TD WIDTH="33%"> </TD> </TR> </TABLE> </body> I then tried to change the form to use an image instead of the default button. Obviously I didn't do it right. THIS ONE DOES NOT WORK. When you choose a menu item and then click the image, it just refreshes the page. Published page: http://www.keylimecomputerservice.co.../modified.html This is the modified code.: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <SCRIPT LANGUAGE="JavaScript"><!-- function openURL() { // grab index number of the selected option selInd = document.theForm.aaa.selectedIndex; // get value of the selected option goURL = document.theForm.aaa.options[selInd].value; // redirect browser to the grabbed value (here a URL) top.location.href = goURL; } //--> </SCRIPT> </head> <body> <TABLE SPAN="3" BORDER=1 CELLSPACING=0 CELLPADDING=0 align="center"> <TR> <TD WIDTH="33%"> <center><font color="black">Choose a connection</font></center><br> <form name="theForm"> <tt> <center> <select name="aaa" size="1"> <option selected value="#"> ---------- </option> <option value="/remote/connect1.exe">Connection 1</option> <option value="/remote/connect2.exe">Connection 2</option> <option value="/remote/connect3.exe">Connection 3</option> <option value="/remote/connect4.exe">Connection 4</option> <option value="/remote/connect5.exe">Connection 5</option> <option value="/remote/connect6.exe">Connection 6</option> <option value="/remote/connect7.exe">Connection 7</option> <option value="/remote/connect8.exe">Connection 8</option> </select> </center> </TD> <TD WIDTH="33%"> <input type="image" src="connectbutton.jpg" onClick="openURL()"> </tt> </form> </TD> <TD WIDTH="33%"> </TD> </TR> </TABLE> </body> Any and all help is appreciated. Runout74 Hi All! Thanks in advance to any and all who help me. What we are trying to do is have a form where customers can use a conditional logic based form that upon submission will redirect to checkout with an appropriate product bundle being populated in the shopping cart. I have some experience with creating forms, in fact I have made a decent form that I have modified from an online form builder... the problem is I have no idea how to auto-fill the shopping cart... period. From what I have read in my research this should be a function of Javascript. I have a decent working knowledge of php, and html, but I am pretty clueless when it comes to Javascript, if anyone could point me in the right direction for this project I would really appreciate it. Hello 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, 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? I have some asp:radiobutton lists that need to update a label with the sum of their values each time a user selects a new value. I am brand new to javascripting and would like some insight on how to get this done. I have inserted my code below. Code: <asp:Label runat="server" Text="Greeting:" /> <asp:Label runat="server" ForeColor="Red" ID="lbl_GreetingScore" Text="0" /> <asp:RadioButtonList ID="rdb1_1" runat="server" RepeatDirection="Horizontal"> <asp:ListItem Selected="True" Text="N/A" Value="4" /> <asp:ListItem Text="Yes" Value="4" /> <asp:ListItem Text="No" Value="0" /> </asp:RadioButtonList> Hey javascript newbie, Im trying to figure out how to add different radio if its selected or not example: Radio_Button1 value="5": Selected Radio_Button2 value="15": Not Selected Radio_Button3 value="25": Selected Radio_Button4 value="35": Selected var addingitup = ??? and im lost???? Good day all, I was hoping someone could help me out with the following. I currently have a slideshow that as thumbnails under a main image. The thumbnails slide left and right with hover on a button and with a click changes main image without any problems. Few things I am looking to change/add: 1. The ability to mouse over the main image and have the caption appear than disappear when the mouse is moved off. Currently I have the caption as a static text under the main image. 2. Start the thumbnail position in the middle instead of the left 3. Add mouseover buttons to the main image to give the ability to cycle through the images instead of having to always use the thumbnails. Below I've include the Javascript code: Is this the best way or is there a better way? Example of slideshow: http://neileverosborne.com/portfolios/manatees.html JAVASCRIPT: Code: var displayWaitMessage=true; // Display a please wait message while images are loading? var activeImage = false; var imageGalleryLeftPos = false; var imageGalleryWidth = false; var imageGalleryObj = false; var maxGalleryXPos = false; var slideSpeed = 0; var imageGalleryCaptions = new Array(); function startSlide(e) { if(document.all)e = event; var id = this.id; if(this.id=='arrow_right'){ slideSpeedMultiply = Math.floor((e.clientX - this.offsetLeft) / 5); slideSpeed = -1*slideSpeedMultiply; slideSpeed = Math.max(-10,slideSpeed); }else{ slideSpeedMultiply = 10 - Math.floor((e.clientX - this.offsetLeft) / 5); slideSpeed = 1*slideSpeedMultiply; slideSpeed = Math.min(10,slideSpeed); if(slideSpeed<0)slideSpeed=10; } } function releaseSlide() { var id = this.id; slideSpeed=0; } function gallerySlide() { if(slideSpeed!=0){ var leftPos = imageGalleryObj.offsetLeft; leftPos = leftPos/1 + slideSpeed; if(leftPos>maxGalleryXPos){ leftPos = maxGalleryXPos; slideSpeed = 0; } if(leftPos<minGalleryXPos){ leftPos = minGalleryXPos; slideSpeed=0; } imageGalleryObj.style.left = leftPos + 'px'; } setTimeout('gallerySlide()',20); } function showImage() { if(activeImage){ activeImage.style.filter = 'alpha(opacity=50)'; activeImage.style.opacity = 0.5; } this.style.filter = 'alpha(opacity=100)'; this.style.opacity = 1; activeImage = this; } function initSlideShow() { document.getElementById('arrow_left').onmousemove = startSlide; document.getElementById('arrow_left').onmouseout = releaseSlide; document.getElementById('arrow_right').onmousemove = startSlide; document.getElementById('arrow_right').onmouseout = releaseSlide; imageGalleryObj = document.getElementById('theImages'); imageGalleryLeftPos = imageGalleryObj.offsetLeft; var galleryContainer = document.getElementById('galleryContainer'); imageGalleryWidth = galleryContainer.offsetWidth - 20; maxGalleryXPos = imageGalleryObj.offsetLeft; minGalleryXPos = imageGalleryWidth - document.getElementById('slideEnd').offsetLeft; if (navigator.userAgent.indexOf('MSIE') >= 0) { var arrowWidth = document.getElementById('arrow_left').offsetWidth; var el = document.createElement('div'); el.style.position = 'absolute'; el.style.left = arrowWidth + 'px'; el.style.width = (galleryContainer.offsetWidth - arrowWidth * 2) + 'px'; el.style.overflow = 'hidden'; el.style.height = '100%'; document.getElementById('galleryContainer').appendChild(el); el.appendChild(document.getElementById('theImages')); } var slideshowImages = imageGalleryObj.getElementsByTagName('IMG'); for(var no=0;no<slideshowImages.length;no++){ slideshowImages[no].onmouseover = showImage; } var divs = imageGalleryObj.getElementsByTagName('DIV'); for(var no=0;no<divs.length;no++){ if(divs[no].className=='imageCaption')imageGalleryCaptions[imageGalleryCaptions.length] = divs[no].innerHTML; } gallerySlide(); } function showPreview(imagePath,imageIndex){ var subImages = document.getElementById('previewPane').getElementsByTagName('IMG'); if(subImages.length==0){ var img = document.createElement('IMG'); document.getElementById('previewPane').appendChild(img); }else img = subImages[0]; if(displayWaitMessage){ document.getElementById('waitMessage').style.display='inline'; } document.getElementById('largeImageCaption').style.display='none'; img.onload = function() { hideWaitMessageAndShowCaption(imageIndex-1); }; img.src = imagePath; } function hideWaitMessageAndShowCaption(imageIndex) { document.getElementById('waitMessage').style.display='none'; document.getElementById('largeImageCaption').innerHTML = imageGalleryCaptions[imageIndex]; document.getElementById('largeImageCaption').style.display='block'; } window.onload = initSlideShow; |