JavaScript - Javascript Checkbox Confirm
Hello,
I'm new to Javascript, but have been programming in PHP and other web codes for 4 years now. I was wondering how you would check if a checkbox was ticked, upon its selection and then unhide HTML content, and then hide such content when deselected.. So far I have this: Code: <script type="text/javascript"> function Agree() { document.getElementById("stepTwo").className = ""; } </script> Which is called by onclick="Agree()" on the select box itself.. I understand an if statement is needed, but how would one go about doing this as my if statements do not appear to be working. Similar TutorialsHi I really really really need your help since I have no idea about this. How can I insert the Javascript Confirmation Alert into the del.php file? I have this del.php file PHP Code: <?php require ("include/config.php"); $id=$_REQUEST['id']; $strSQL = "DELETE FROM change WHERE id = '".$id."' "; $objQuery = odbc_exec($conn,$strSQL); if($objQuery) { echo "<script language='Javascript'>alert('Deleted.'); window.location=\""."index.php?action=syif\"</script>"; } else { echo "Error Delete [".$strSQL."]"; } odbc_close($conn); ?> This is the confirmation javascript Code: <html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Delete?"); if (r==true) { alert("Deleted!"); } else { alert("Cancelled!"); } } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" /> </body> </html> http://tinyurl.com/bw2y3sr This is my site and I want to create a Yes and No dialogue box when user closes a browser so this popup confirm dialogue should appear. Can anyone help me? I am having some difficulty in constructing a window.confirm() function that works with my code. So if the form data is valid, I need to use a window.confirm() dialog box to show the user's total cost based on the rental rate of equipment chosen and the reservation period. The user must accept the cost by pressing the confirm button, and if user cancels do not submit data. I have written this code but cannot figure out how to find the number of days from the 2 date fields and use that to calculate and display the total cost. Any help with this will be greatly appreciate. Thanks so much. [This is the part I am having trouble with:] //confirm submit and display rental cost Code: var equip = document.forms[0].equipment.value var pDate = document.forms[0].pickupDate.value var pHours = document.forms[0].pickupHours.value var pMinutes = document.forms[0].pickupMinutes.value var rDate = document.forms[0].returnDate.value var rHours = document.forms[0].returnHours.value var rMinutes = document.forms[0].returnMinutes.value var pTime = pHours + pMinutes var rTime = rHours + rMinutes var total = (((rDate - pDate) - 1) * 24) * equip) + ((rTime + (24 - pTime)) * equip) function confirmSubmit() { var submitForm = window.confirm("'The total rental cost is: ' + total"); if (submitForm == true) return true; return false; } [Below is the code I have so far:] 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> <!-- Brooks Rogalski December 6, 2010 --> <title>ABC Outdoor Sports</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <script type = "text/javascript"> /* <![CDATA[ */ //image slideshow function var interval = 4000; // delay between rotating images var random_display = 1; // 0 = no, 1 = yes var pause = false; var image_index = 0; image_list = new Array(); image_list[image_index++] = new imageItem("fishing.jpg"); image_list[image_index++] = new imageItem("biking.jpg"); image_list[image_index++] = new imageItem("climbing.jpg"); image_list[image_index++] = new imageItem("kayaking.jpg"); image_list[image_index++] = new imageItem("scuba.jpg"); var number_of_image = image_list.length; function imageItem(image_location) { this.image_item = new Image(); this.image_item.src = image_location; } function get_ImageItemLocation(imageObj) { return(imageObj.image_item.src) } function generate(x, y) { var range = y - x + 1; return Math.floor(Math.random() * range) + x; } function getNextImage() { if (pause == true) return; if (random_display) { image_index = generate(0, number_of_image-1); } else { image_index = (image_index+1) % number_of_image; } var new_image = get_ImageItemLocation(image_list[image_index]); return(new_image); } function rotateImage(place) { var new_image = getNextImage(); document[place].src = new_image; var recur_call = "rotateImage('"+place+"')"; setTimeout(recur_call, interval); } //validate form functions function validateForm() { var valid = true; //validate equipment if (document.forms[0].equipment.selectedIndex == 0) { window.alert("Please select your equipment type."); document.forms[0].equipment.focus(); return false; } //validate pick-up date if (document.forms[0].pickupDate.value == "'' || '(mm/dd/yyyy)'" ) { window.alert("Please enter your Pick-up Date."); document.forms[0].pickupDate.focus(); valid = false; return valid; } today = new Date(); year = today.getFullYear() ; month = today.getMonth(); day = today.getDate(); //validate pickup date format var re =/^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/ if(document.forms[0].pickupDate.value != '' && !document.forms[0].pickupDate.value.match(re)) { window.alert("Invalid date format: " + document.forms[0].pickupDate.value); document.forms[0].pickupDate.focus(); valid=false; return valid; } var date; var input2=document.forms[0].pickupDate.value; var cyear = parseInt(input2.substring(6,10)); var cmonth = parseInt(input2.substring(0,2)) - 1; var cday = parseInt(input2.substring(3,5)); if ( month < cmonth ){ date = year - cyear - 1; } else if ( month < cmonth ){ date = cyear - year; } else if ( month == cmonth ){ if ( cday < day ){ date = cyear - year - 1; } else if ( day > cday ){ date= cyear - year; } else if ( day == cday ){ date = cyear - year-1; } } if(date < 2){ window.alert('Must be atleast 2 days from today'); valid=false; return valid; } //validate pick-up time hours if (document.forms[0].pickupHours.selectedIndex == 0) { window.alert("Please select the number of hours for pick-up time."); document.forms[0].pickupHours.focus(); return false; } //validate pick-up time minutes if (document.forms[0].pickupMinutes.selectedIndex == 0) { window.alert("Please select the number of minutes for pick-up time."); document.forms[0].pickupMinutes.focus(); return false; } //validate return date if (document.forms[0].returnDate.value == "'' || '(mm/dd/yyyy)'" ) { window.alert("Please enter your Return Date."); document.forms[0].returnDate.focus(); valid = false; return valid; } //validate return date format if(document.forms[0].returnDate.value != '' && !document.forms[0].returnDate.value.match(re)) { window.alert("Invalid date format: " + document.forms[0].returnDate.value); document.forms[0].returnDate.focus(); valid=false; return valid; } if(document.forms[0].returnDate.value <= document.forms[0].pickupDate.value){ window.alert("Please choose later date"); valid=false; return false; } //validate return time hours if (document.forms[0].returnHours.selectedIndex == 0) { window.alert("Please select the number of hours for return time."); document.forms[0].returnHours.focus(); return false; } //validate return time minutes if (document.forms[0].returnMinutes.selectedIndex == 0) { window.alert("Please select the number of minutes for return time."); document.forms[0].returnMinutes.focus(); return false; } //validate first name if (document.forms[0].firstName.value=="") { window.alert("Please enter your first name."); document.forms[0].firstName.focus(); valid = false; return valid; } //validate last name if (document.forms[0].lastName.value=="") { window.alert("Please enter your last name."); document.forms[0].lastName.focus(); valid = false; return valid; } //validate street address if (document.forms[0].street.value=="") { window.alert("Please enter your street address."); document.forms[0].street.focus(); valid = false; return valid; } //validate city if (document.forms[0].city.value=="") { window.alert("Please enter your city."); document.forms[0].city.focus(); valid = false; return valid; } //validate zip code if (document.forms[0].zip.value==""){ window.alert("Please enter your zip code."); document.forms[0].zip.focus(); valid=false; return valid; } var re5digit=/^\d{5}$/ if (document.forms[0].zip.value.search(re5digit)==-1){ window.alert("Please enter a 5 digit number") valid=false; return valid; } //validate date of birth if (document.forms[0].date.value == "'' || '(mm/dd/yyyy)'" ){ window.alert("Please enter your date of birth."); document.forms[0].birthDate.focus(); valid=false; return valid; } var reDateFormat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/ if(document.forms[0].date.value.search(reDateFormat)==-1){ window.alert("Please enter a standard format. [mm/dd/yyyy]") valid=false; return valid; } //check if over 18 var age; var input = document.forms[0].birthDate.value; var pyear = parseInt(input.substring(6,10)); var pmonth = parseInt(input.substring(0,2)) - 1; var pday = parseInt(input.substring(3,5)); if ( month < pmonth ){ age = year - pyear - 1; } else if ( month > pmonth ){ age = year - pyear; } else if ( month == pmonth ){ if ( day < pday ){ age = year - pyear - 1; } else if ( day > pday ){ age = year - pyear; } else if ( day == pday ){ age = year - pyear; } } if(age < 18){ window.alert('Attention: Under 18!'); valid=false; return valid; } //confirm submit and display rental cost var equip = document.forms[0].equipment.value var pDate = document.forms[0].pickupDate.value var pHours = document.forms[0].pickupHours.value var pMinutes = document.forms[0].pickupMinutes.value var rDate = document.forms[0].returnDate.value var rHours = document.forms[0].returnHours.value var rMinutes = document.forms[0].returnMinutes.value var pTime = pHours + pMinutes var rTime = rHours + rMinutes var total = (((rDate - pDate) - 1) * 24) * equip) + ((rTime + (24 - pTime)) * equip) function confirmSubmit() { var submitForm = window.confirm("'The total rental cost is: ' + total"); if (submitForm == true) return true; return false; } } /* ]]> */ </script> </head> <body onload = "rotateImage('rImage')"> <h1> ABC Outdoor Sports Equipment </h1> <img src="fishing.jpg" id="rImage" width="250" height="200" onmouseover = "pause=true;" onmouseout = "pause=false;"> <br/> <br/> <form onsubmit = "return validateForm();" action = "mailto:rogalskibf@gmail.com?subject=ABC Customer Reservation" method="post" enctype="text/plain"> <table border = "0"> <tr> <td> Equipment:<br/> <select name = "equipment"> <option value="unselected">Select Equipment Type</option> <option value = 20>Fishing Boat</option> <option value = 15>Kayak</option> <option value = 2>Mountain Bike</option> <option value = 10>Scuba Gear</option> </select> </td> </tr> <tr> <td> Pick-up Date: <br/> <input type = "text" name = "pickupDate" value = "(mm/dd/yyyy)"/> </td> <td> Pick-up Time: <br/> <select name = "pickupHours"> <option value="unselected">hr</option> <option value = 7>07</option> <option value = 8>08</option> <option value = 9>09</option> <option value = 10>10</option> <option value = 11>11</option> <option value = 12>12</option> <option value = 13>13</option> <option value = 14>14</option> <option value = 15>15</option> <option value = 16>16</option> <option value = 17>17</option> </select> <select name = "pickupMinutes"> <option value="unselected">min</option> <option value = 0>00</option> <option value = .5>30</option> </select> </td> </tr> <tr> <td> Return Date: <br/> <input type = "text" name = "returnDate" value = "(mm/dd/yyyy)"/> </td> <td> Return Time: <br/> <select name = "returnHours"> <option value="unselected">hr</option> <option value = 7>07</option> <option value = 8>08</option> <option value = 9>09</option> <option value = 10>10</option> <option value = 11>11</option> <option value = 12>12</option> <option value = 13>13</option> <option value = 14>14</option> <option value = 15>15</option> <option value = 16>16</option> <option value = 17>17</option> </select> <select name = "returnMinutes"> <option value="unselected">min</option> <option value = 0>00</option> <option value = .5>30</option> </select> </td> </tr> <tr> <td> First Name: <br/> <input type = "text" name = "firstName"/> </td> <td> Last Name: <br/> <input type = "text" name = "lastName"/> </td> </tr> <tr> <td> Street: <br/> <input type = "text" name = "street"/> </td> <td> City: <br/> <input type = "text" name = "city"/> </td> <td> Zip:<br/> <input type = "text" name = "zip" maxlength = "5"/> </td> </tr> <tr> <td> Date of Birth: <br/> <input type = "text" name = "date" value = "(mm/dd/yyyy)"/> </td> </tr> <tr> <td colspan = "3" align = "center"> <input type = "submit" name = "submit" value = "Submit Reservation"/> </td> </tr> </table> </form> </body> </html> Hi everyone. I need a Javascript code for the following: i have a checkbox on my page. when this checkbox got checked, an alert like "Are u sure?" must ask if OK or Cancel. if i click OK the checkbox becomes checked, it runs a javascript function (chkIt() )and refreshes the page. if i click Cancel the checkbox should not became checked and my function will not run. Thanks a lot. Hello, I am not a coder and this has been giving me grief for days My form is located here on page three of the multi form: http://www.rocpinions.com/main-form.html I have been working on this for days and can't figure it out. I have four check boxes. Dog, Cat, Other, and None of These. If Dog Cat and Other (or any combination of) are checked that is fine but if the check box "None of These" is checked I need it to remove the checks from All other boxes. This is an example of exactly what I need my form to do jsfiddle.net/srEuM/ Does anyone know how I can accomplish this with RS Form Pro? Here is the code I am using: Code: <script type="text/javascript"> function checkI() { var checkL = document.getElementsByName('form[PetsInHouse][]'); for (var i=0;i<checkL.length-1;i++) if(document.getElementById('PetsInHouse3').checked){ document.getElementById('PetsInHouse'+i).disabled = true; document.getElementById('PetsInHouse'+i).checked = false; } else { document.getElementById('PetsInHouse'+i).disabled = false; } } </script> This is how I am calling it in the additional attributes in RS Form Pro Code: onclick="checkI();" I am currently using this code above and it only disables all checkboxes when "None of These" is checked but if I check any of the other boxes I can still check "None of These" and that is not the correct functionality. This is exactly what I need to do but in the same format I have above. http://jsfiddle.net/srEuM/ Any help would be greatly appreciated. Thank you Deziner Hello, i want to build a tax calculator's form, i want use a checkbox, so when the checkbox "checked" then the total tax will add the "luxury goods tax" on total tax. this is my code: 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>KasKusbay Order Calculator</title> </head> <SCRIPT language = "javascript"> var currency_rates = new Array(); currency_rates["GBP"]=0.62; currency_rates["CAD"]=0.99; currency_rates["EUR"]=0.75; currency_rates["AUD"]=0.96; function getCurrencyRates() { var currencyRates=0; var theForm = document.forms["myform"]; var selectedCurrency = theForm.elements["currency"]; currencyRates = currency_rates[selectedCurrency.value]; return currencyRates; } function addPbm() { var PbmService=0; var theForm = document.forms["myform"]; var pbm = theForm.elements["pbm"]; if(pbm.checked==true) { pbmService = [J]; } return pbmService; } function addPbm() { var PbmService=0; var theForm = document.forms["myform"]; var pbm = theForm.elements["pbm"]; if(pbm.checked==true) { pbmService = [J]; } return pbmService; } function ceiling( num, at ) { var temp = num / at; // 523/50 ==>> 10.46 return Math.ceil(temp) * at; // ceil(10.46 ==>> 11, 11 * 50 ==>> 550 } function calculateTotal() { var X; var form = document.myform; var A = form.price.value.replace(/[^\d\.]/g, ""); form.price.value = A; var B = form.shipping_cost.value.replace(/[^\d\.]/g, ""); form.shipping_cost.value = B; var F = (parseFloat(A) + parseFloat(B)) * getCurrencyRates(); var C = Number(F) * parseFloat("0.1"); form.total.value = C.toFixed(2); var G = Number(F) + Number(C); var H = Number(G) * parseFloat("0.05") form.p2.value = H.toFixed(2); var I = Number(G) * parseFloat("0.03") form.p3.value = I.toFixed(2); var J = Number(G) * parseFloat("0.2") form.p4.value = J.toFixed(2); X = Number(C) + Number(H) + Number(I) + addPbm(); form.total_IDR.value = X.toFixed(2); //exp: ceiling: document.jslearnform.total_USD.value = Math.ceil(X); //or decimal: document.jslearnform.total_USD.value = X.toFixed(2); //or even document.jslearnform.total_USD.value = Math.ceil(X).toFixed(2); } </SCRIPT> <body> <form name="myform" method="post" action=""> <table width="93%" border="0" id="form_table2"> <tr> <th width="24%"><p>Price ›</p></th> <td width="37%"><p> $ <input type="text" size="7" id="price" name="price" /> <select id="currency" name="currency" onchange="calculateTotal()"> <option value"gbp">GBP</option> <option value"cad">CAD</option> <option value"eur">EUR</option> <option value"aud">AUD</option> </select> <br /> Input Price and Currency</p></td> <td width="39%" rowspan="3"><p align="right">Duty <input type="text" style="background-color: #DCDDDD;" size="12" id="total" readonly name="total" value="" /> </p> <p align="right">Sales Tax <input type="text" style="background-color: #DCDDDD;" size="12" id="p2" readonly="readonly" name="p2" value="" /> </p> <p align="right">Income Tax <input type="text" style="background-color: #DCDDDD;" size="12" id="p3" readonly="readonly" name="p3" value="" /> </p> <p align="right">Luxury Goods Tax <input type="text" style="background-color: #DCDDDD;" size="12" id="p4" readonly="readonly" name="p4" value="" /> </p></td> </tr> <tr> <th>Shipping Cost ›</th> <td> $ <input type="text" size="7" id="shipping_cost" name="shipping_cost" /> <br /></td> </tr> <tr> <th>Kind ›</th> <td><select id="currency3" name="currency2" onchange="calculateTotal()"> <option value="value""EL">Electronic</option> <option value="value""NL">Apparel</option> </select> <br /> <input type="checkbox" id="pbm" name="pbm" /> Luxury Item</td> </tr> <tr> <th>Tax ›</th> <td><div align="center"> <input type="text" style="background-color: #DCDDDD;" size="14" id="total_IDR" readonly name="total_IDR" value="" /> </div></td> <td> </td> </tr> <tr> <th> </th> <td><div align="center"> <input type="button" value="Calculate" onclick = "javascript:calculateTotal()" /> <input type="reset" value="Reset" /> </div></td> <td><div align="center"></div></td> </tr> </table> </form> </body> </html> But i have problem with the function command, the total tax doesn't appear, seems i made wrong function code on function adPbm(). Code: function addPbm() { var PbmService=0; var theForm = document.forms["myform"]; var pbm = theForm.elements["pbm"]; if(pbm.checked==true) { pbmService = [J]; =====> anyone can help me correct this coding? } return pbmService; } Thank you for anyone could help. sir i have a problem in is page. i want to have a javascript function that call on checkbox on click event. if checked firstly a 125 x125 sized checkbox then i want to restrict that all checkbox that i checked later must 125 x 125 sized if i checked 250 x250 sized checkbox then create a alert message pleas select 125 x 125 sized , i also have function plz check it function validate(f) { var array = new Array(); for(var i = 0; i < document.delet.checkbox.length; i++){ var ele = document.delet.checkbox; if( ele[i].checked){ var size = document.getElementById(f).value; array[i]=size; alert(array[0]); /*if(array[0] == array[i]){ alert("size is equal"); }else if(){ alert("size is not equal"); }*/ }//end if }//end for //if(first_size != second_size){alert(second_size); return false;} }//end function this is a one row and repeated in while loop php script, row code is below. Code: <tr bgcolor="<?php echo $color;?>"> <td align="center"> <input name="checkbox[]" type="checkbox" id="checkbox" value="<?php echo $aaa['id']; ?>" onclick=" return validate('<?php echo $id; ?>');" /></td> <td align="center"><?php echo $aaa['imgSize'];?><input type="hidden" id="<?php echo $id; ?>" name="size" value="<?php echo $aaa['imgSize'];?>" /></td> </tr> <?php }//end while ?> this is a online page plz check it http://hkcsy.com/ads Hello! I have modified the create_account.php page of an osCommerce store, and I added 4 checkboxes for the 4 terms that the customers must agree to. If not checked, the error message should come up (same for each - doesn't matter)> ok nevermind it's actually working now. I am fairly new to javascript and am attempting to create a function that will clear one checkbox when another is checked. I have multiple forms with dynamically generated names on the page. Here is what I have: <script type="text/javascript"> function undo_Complete(myForm) { var formName = myForm.name; if(document.formName.getElementsByName("Needs_Change").checked==true) { document.formName.getElementsByName("Complete").checked=false; } } </script> The two checkbox fields involved: <input name="Complete" value="Yes" <?php echo($Complete=="Yes") ? "checked" : ""; ?> size="4" type="checkbox"> <input name="Needs_Change" value="Yes" <?php echo($Needs_Change=="Yes") ? "checked" : ""; ?> size="4" type="checkbox" onClick="undo_Complete(this.form)"> Could someone please tell me what I am doing wrong? Thank you! Lisa Guys, For some reason my script only works when I have at lease two checkboxes. To simulate the problem just run it once with two html input checkbox elements -> check one checkbox and press submit -> it works -> Now remove one input checkbox field and check the remaining checkbox & submit -> Bamm doesn't work... What am I doing wrong ? Code: <html> <head> <script> function Check(chk) { for (i=0; i < chk.length; i++) chk[i].checked=document.ListActionForm.Check_ctr.checked ; } function desubmit() { if(get_args()==false) {alert("nothing_selected");return false;} if(labelling(true)) return false; } function labelling(s) {return true;} function get_args() { s=chkboxa2str(document.ListActionForm['listaction[]']); if(s)alert(s); if(s.length<8)return false; else return s; } function chkboxa2str(chkbox_a) { var list = ""; for(var i = 0; i < chkbox_a.length; i++){ if(chkbox_a[i].checked) { list += chkbox_a[i].value + " "; } } return list; } </script> </head> <body> <form action="?h=1296078874" method="post" name="ListActionForm" onsubmit="return desubmit()"> <input type='checkbox' name='listaction[]' value='2010102909103530'> Testbox 1<br> <input type='checkbox' name='listaction[]' value='2010102909103532'> Testbox 2<br> <input type="Submit" name="Submit" value="Versturen" > </form> </body> </html> Im creating a portfolio site for myself that my have gotten a little too ambitious but I'd still like to make this work. My main site loads a video demo reel using the new <video> tag and to make it look cooler has an "ambilight" television effect around it. For usability and for users that find it annoying or distracting I want a toggle to turn the effect off. I have my checkbox created as well as all the effects working for it. Here is a piece of the main code as well as a link to the ambilight.js file Code: <label name="ambilightToggle"> <input type="checkbox" name="toggle"/> <div class="toggle-switch"> <div class="handle"></div> <div class="track"> <span>OFF</span><span>ON</span> </div> </div> </label> </div> </div> <div id="main" class="clearfix"> <div id="video-edge"> <img id="ribbon" width="112" height="112" alt="Demo Reel Ribbon" src="img/ribbon-demoreel.png"> <div id="video-wrap" class="video-js-box moo-css"> <video id="example" class="video-js" width="720" height="405" controls preload poster="posters/poster_demoreel2010.png"> <source src="video/demoreel2010.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' /> <source src="video/demereel2010.webm" type='video/webm; codecs="vp8, vorbis"' /> <source src="video/demoreel2010.ogv" type='video/ogg; codecs="theora, vorbis"' /> </video> </div> </div> <script type="text/javascript"> ambiLight.create(document.getElementById('example')) </script> Portfolio Page http://www.eschulist.com/test/js/ambilight.js I was able to make the ambilight effect go away using this, but it only works for a second as the video continues to play and the new lights are redrawn. Code: <script type="text/javascript"> $(document).ready(function(){ $(this).click(function(){ $('canvas.ambilight-left, canvas.ambilight-right').addClass('goAway'); }); }); </script> Any other ideas on what to do? If the click function works I should be able to have it check the checkboxes state and have it persist. Maybe? URL: https://medicard1.com/services.html Site also employs CodeIgniter from original developer. Code below sets up a table with a form and script in separate cells of the same row. Looks good and click on check box works ok, but script seems to only run when the page is initially loaded. Does not change variable 'c' and display the change. Am in a bind for this one. My developer is away for the holiday and CEO wants it done ASAP. Anyone have an idea? <!-- Setup a table to hold the elements where I want them without conflicting with CodeIgniter - K.I.S.S.--> <table style="border:0px;"> <tr> <td style="width:600px; text-align:left;"> <!-- Un-submitted form with legend and checkbox input to acknowledge terms and display discount code --> <form name="acknowledge" action="" method=""> <legend>I acknowledge that I have read and understand the content of this page <!-- onClick should execute display_code() script --> <input style="border:0px; width:40px;" type="checkbox" name="investor" onClick="display_code()"/> </legend> </form> </td> <td style="width:200px; text-align:right;"> <!-- Script should check checked state of checkbox investor and set c to appropriate value --> <script type="text/javascript"> <!-- set c="" after get this working --> var c="NOT SET"; function display_code() { if (document.acknowledge.investor.checked) { var c="INVESTOR"; } else { <!-- set c="" after get this working --> var c="NO CODE"; } } document.write('Your code is: ' + c); </script> </td> </tr> </table> Firstly, I'm a complete Javascript noob, so apologies if this is blindingly simple. I'm trying to write a piece of javascript that will check a single checkbox depending on a dynamically-imported piece of information further up the page. The page will look like this: Code: <div id="title"> <p class="white">1</p> </div> <div id="question"> <p>Please indicate your area(s) of interest below:<br /> <input type=checkbox value="1" /> Option 1<br /> <input type=checkbox value="2" /> Option 2<br /> <input type=checkbox value="3" /> Option 3<br /> <input type=checkbox value="4" /> Option 4</p> </div> The variable which indicates which checkbox should already be checked is in the div 'title' in the p class 'white'. So in the case above, when the page loads the 'Option 1' checkbox should already be checked. The javascript i have, rather poorly, cobbled together so far just doesn't work, and I was wondering if anyone could point me in the direction of some useful tutorials. All the tutorials I have read so far deal with mass checking all the boxes with a button click. Hello I am new at Javascript. Please help me this: I have a form and a checkbox: Code: <input name="pass" type="password" class="textfield" /> <input type="checkbox" class="check"> Click here to show/hide password If I the checkbox is checked, it will show the password in the form, it means Code: <input name="pass" class="textfield" /> if not, the input form is: Code: <input name="pass" type="password" class="textfield" /> Hi all, I use a javascript to generate a checkbox list. It works well but all the <input type="checkbox"> generated have the same id. I would like to find a way to auto-implement the id (with a unique id). So if my javascript generates 10 checkboxes, I will get id from 1 to 10 or something similar. Code: // here I build the filter checkboxes based on all the class names $.each(arrayUniqueClasses, function() { $('<li><input class="styled" type="checkbox" checked="checked" name="1" value="'+this+'" id="1" /> <label class="check" for="1"></label> <label class="info" for="filterID'+this+'">'+this+'<\/label><\/li>').appendTo('ul.filters'); }); so I tried something but it doesn't work at all (I'm a beginner as you can guess) : Code: var getUniqueId = (function () { var id=0; return function() { if (arguments[0]==0) id=0; return id++; } } )(); Thanks for helping here the full script if needed : Code: function unique(a) { tmp = new Array(0); for(i=0;i<a.length;i++){ if(!contains(tmp, a[i])){ tmp.length+=1; tmp[tmp.length-1]=a[i]; } } return tmp; } function contains(a, e) { for(j=0;j<a.length;j++)if(a[j]==e)return true; return false; } function removeItems(array, item) { var i = 0; while (i < array.length) { if (array[i] == item) { array.splice(i, 1); } else { i++; } } return array; } $(document).ready(function () { if ($('.filterThis > li').length < 2) { return; } var stringOfClassNames = ''; $('.filterThis > li').each( function (i) { var thisClassString = $(this).attr('class'); stringOfClassNames = stringOfClassNames +' '+ thisClassString }); stringOfClassNames = jQuery.trim(stringOfClassNames); var arrayClasses = stringOfClassNames.split(' '); var arrayClasses = arrayClasses.sort(); totalNumberOfItemsToFilter = $('.filterThis > li').length; var result = new Object(); for (var filterClass in arrayClasses) { if (result[arrayClasses[filterClass]] === undefined) { result[arrayClasses[filterClass]] = 1; } else { result[arrayClasses[filterClass]]++; } } var resultsToRemoveFromFilters = new Array(); for (var item in result) { if (result[item] == totalNumberOfItemsToFilter) { resultsToRemoveFromFilters.push(item); } } arrayUniqueClasses = (unique(arrayClasses)); if (arrayUniqueClasses.length > 1) { $('<ul class="filters"><\/ul>').insertAfter('h3'); $.each(arrayUniqueClasses, function() { $('<li><input class="styled" type="checkbox" checked="checked" name="1" value="'+this+'" id="0" /><label class="check" for="0"></label><label class="info" for="filterID'+this+'">'+this+'<\/label><\/li>').appendTo('ul.filters'); }); var classesStringOfSin = new Array(); classesStringOfSalvation = arrayUniqueClasses; $('.filterThis > li').addClass('filterTriggerShown'); $('.filters input').click( function() { var value= $(this).val(); stringValue = '.filterThis > li.'+value; if ($(this).is(':checked')) { classesStringOfSalvation.push(value); classesStringOfSin = removeItems(classesStringOfSin, value); $(stringValue).removeClass('filterTriggerHidden').addClass('filterTriggerShown').slideDown(); } else { classesStringOfSin.push(value); classesStringOfSalvation = removeItems(classesStringOfSalvation, value); $(stringValue).removeClass('filterTriggerShown').addClass('filterTriggerHidden'); $.each(classesStringOfSalvation, function() { var newStringValue = stringValue+'.'+this; $(newStringValue).removeClass('filterTriggerHidden').addClass('filterTriggerShown'); }); $('.filterTriggerHidden').slideUp(); } }); } }); Guys Need Help here... here i send attach my script. i need combine 2 function script into . but i can figure it out. can everyone helps me. Code: <?php require_once('../Connections/koneksi.php'); ?> <!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> <script> function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; switch(newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; } } } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { if(rowCount <= 1) { alert("Cant delete all rows"); break; } table.deleteRow(i); rowCount--; i--; } } }catch(e) { alert(e); } } function selectnama() { var i = 0; i = document.form1.txtcustomer.value; i= i.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' '); //alert(cust[i]); document.form1.select2.value = i; } function change2() { document.form1.txtcustomer.value = document.form1.select2.value; } function enable_text(status) { status=!status; document.form1.qty_material.disabled = status; } </script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form name="form1" method="post" > <table id="dataTable" width="auto" style="margin:-4px 0 0 0;" cellspacing="6"> <tr> <td style="width:20px;"><INPUT type="checkbox" name="chk" /></td> <td> <input type="text" name="txttipe[]" placeholder="Tipe" id="txttipe" size="40"/> / <input name="txtcustomer" type="text" id="txtcustomer" onkeyup="selectnama()" size="10" maxlength="10"/> <select name="select2" style="color:blue;" onchange="change2()" > <option></option> <?php $query = mysql_query("select right(KUNNR,6), NAME1 from kna1 order by NAME1") or die(mysql_error()); $query3 = mysql_query("select * from spg_kna1_exception order by NAME1") or die(mysql_error()); while($row = mysql_fetch_array($query)) { echo "<option value=".$row[0].">$row[1] - $row[0]</option>"; } while($row3 = mysql_fetch_array($query3)) { echo "<option value=".$row3[0].">$row3[1] - $row3[0]</option>"; } ?> </select>; <input type="checkbox" name="qty_matnr" onClick="enable_text(this.checked)" > Qty <input type="text" name="qty_material"> </td> </tr> </table> <INPUT type="button" value="Add Model" onclick="addRow('dataTable')" /> <INPUT type="button" value="Delete Model" onclick="deleteRow('dataTable')" /> </form> </body> </html> Ok, I need some help with this. When you click the close button on your browser, I want it to have a confirmation. Saying "**Click OK to be redirected to a new page**" something like that. If you click "OK" you are redirected to another page. If you hit CANCEL, then it closes out. It doesn't have to be a confirmation. Just needs to be something that has an option. (Maybe return xx?) Anyways, here's what I've got: Code: <script type="text/javascript" language="javascript"> var sure = false; var lin = false; function sureF() { if(!sure && !lin) { sure = true; var con = confirm("**Are you sure you want to leave?**") if(con == true) { location.href = "http://www.google.com/" return con; } else { alert("Sorry") } } } window.onbeforeunload = sureF; </script> What that does, is when you click close on your browser, it will say "Are you sure you want to leave?" you click "OK", and you get redirected to google .com (How I set it) BUT then a popup comes up saying, "Are you sure you want to navigate away?" which I don't want at all. As you can see, my script is quite messed up. Could you help me out? Thanks. Hi, I am trying to give the user the option of music on my homepage (b/c we've all found it annoying at times...perhaps most times). I have found an "onload" option for the body tag on dotnetspider.com, but it doesn't seem to be working for me. Please take a look and let me know of any improvements I could make. Thx Code: <body onload="loadMusic()"> <p> <script type="text/javascript"><!-- function loadMusic() { var r=confirm("Would you like a background tune?"); if (r==true) { <input type="button" onclick="show_confirm()" value="Show a confirm box" /> <object class="plugin_video" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="480" width="640"> <param name="autoplay" value="false" /><embed title="QuickTime" hidden="true" src="sounds/siteBG.wav" mce_src="sounds/siteBG.wav" autoplay="true" loop="true" controller="true"></embed> </object> } else { alert("If you change your mind reload the page to choose again."); // --></script> Hello, this is not and advert This is a class i built in javascript What it dose: When users leave a site that has a confirm you want to leave box from the browser Why have i posted: I have seen around on the internet posts about how to do such a thing so i though i would get hits to codding forum when user search for such a thing and any one of codding forum members could help it get better Well this is a nice little object to use insted that dose a light box effect and brings up a Yes/no true/false box you set what you want it to say The JSON Object PHP Code: confirmBox = { 'message' : 'This is a Confirm Box', 'trueTxt' : 'True', 'complete' : true, 're' : '', 'falseTxt' : 'False', 'onTrue' : 'alert("true")', 'onFalse' : 'alert("false")', 'setTrue' : function(ontrue){ this.onTrue = ontrue + "confirmBox.update('true')"; }, 'setFalse' : function(onfalse){ this.onFalse = onfalse + "confirmBox.update('false')"; }, 'setTrueText' : function(trueText){ this.trueTxt = trueText; }, 'setFalseText' : function(falseText){ this.falseTxt = falseText; }, 'setText' : function(text){ this.message = text; }, 'hide' : function(){ var bg = document.getElementById('___confirmBox_bg'); var center = document.getElementById('___confirmBox_center'); var dialog = document.getElementById('___confirmBox_dilog'); center.removeChild(dialog); bg.removeChild(center); document.body.removeChild(bg); }, 'show' : function(){ this.createBG(); this.createCenter(); this.createDialog(); }, 'update' : function(sw){ this.re = sw; }, 'state':function(){ if(this.re = ''){ return false; }else{ return this.re; } }, 'createBG' : function(){ var bg = document.createElement("div"); bg.setAttribute('style', "display: table; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80);"); bg.setAttribute('id', '___confirmBox_bg'); document.body.appendChild(bg); }, 'createCenter' : function(){ var center = document.createElement('div'); center.setAttribute('style',"#position: absolute; #top: 50%; display: table-cell; vertical-align: middle; margin-left:auto; margin-right:auto;"); center.setAttribute('id', '___confirmBox_center'); document.getElementById('___confirmBox_bg').appendChild(center); }, 'createDialog' : function(){ var dialog = document.createElement('div'); dialog.setAttribute('style', "display:block; width: 300px; padding: 16px; background-color: white; z-index:1003; margin-left:auto; margin-right:auto;"); dialog.setAttribute('id', '___confirmBox_dilog'); dialog.innerHTML = this.message + '<div align="right"><input type="button" onclick="eval(confirmBox.onTrue); confirmBox.hide();" value="' +this.trueTxt + '" /><input type="button" onclick="eval(confirmBox.onFalse); confirmBox.hide();" value="' + this.falseTxt + '" /></div>'; document.getElementById('___confirmBox_center').appendChild(dialog); }, } Then this is how you call it and set propertys Code: <script src="confirmBox.js" type="text/javascript"></script> <script type="text/javascript"> confirmBox.setText("This is a test"); //Sets the text to show in the box confirmBox.setTrueText("I can see it"); // sets the text on the return true button confirmBox.setFalseText("I can't see it"); // sets the text on the return false button confirmBox.setTrue('alert("Thanks");'); //what to do when true is clicked confirmBox.setFalse('alert("Your a lier");');// what to do when false is clicked confirmBox.show(); // Show the confirmBox </script> |