JavaScript - How To Print The Values Of The Form Data?
Hi there,
I'm absolute newbie in javascript, so the question may look not worth asking for you. Sorry for that. My situation is like that: I want to make a preview of form data using javascript. After the button "preview" is clicked I start showing div dialog which should contain data entered by users. The problem is that because my div dialog is coded in the same page as form I can get only default values. It means - after making some changes, they are not visible. To get and print the value of input I use this code: Code: <script type="text/javascript"> mytext = document.getElementById('name').value; document.write(mytext); </script> How it would be possible to update the values on "on click" event. Thank you very much for considering this question. Similar TutorialsHi guys, hoping you can help me out again, with this new problem. I've got a form which is acting as a calculator. Once the calculation is complete I want it so when the user presses a 'print' button it takes certain parts of the form data and displays them in a new window which would be designed for printing. how can i go about this using only javascript? thanks Hi, Ours is a web based application. In a particular use case, print-receipt; we pull up data from database and display it a new window ... followed by a javascript::window.print() To print the content. But this prints the browser window - in graphic mode. The target printer, attached to the browser machine is a Dot matrix printer; and consumes a lot off time to print a single window (because of the graphic nature) Can the printing be done in text mode ? thank you. jeevan Complete newbie to JS, If button is clicked, want form to be validated. If the validation passes then bring up print dialogue I have got the validation (using dreamweaver) working, however if the form is correct , how do I get the print dialogue (window.print()) to appear? here's the code Code: <script language="JavaScript" type="text/JavaScript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_validateForm() { //v4.0 var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); if (val) { nm=val.name; if ((val=val.value)!="" ) { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } //--> </script> Code: <td><input name="Name" type="text" id="Name" size="50" maxlength="50"></td> <input name="Button" type="button" onClick="MM_validateForm('Name','','R');return document.MM_returnValue" value="Button" /> I have a order form page and on submitting it opens a new web page that displays the order totals. Below is my code and most probably wrong but for me it seems logic. Please assist. Order Form: Code: <td colspan="1" height="120" align="left"> <select style="margin-left: 60px; background-color: #00FF77;" name="prod_bed_359" onchange="calculateValue(this.form)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> R359</td></tr> New page I called a unction to print: Code: function itemsOrdered() { var beds = document.forms[2].prod_bed_359.value; document.write("<pre><strong>Description\t\tQuantity\tPrice</strong></pre>"); document.write("<pre>Doggie Bed\t\t" + beds + "</pre>"); } This is still basic as I need to get this right before adding the prices and totals which is also extracted from the order page. I set some value like in onbeforeUnload document.getElementById('hGridStateModified').value='YES'; The value is not set and is not available at server side. ( I set some value like document.getElementById('hGridStateModified').value='YES'; The value is available at server side. ) Code /// START f(window.body){ window.body.onbeforeunload = saveBeforeExit; // IE else }else{ window.onbeforeunload = saveBeforeExit; // FX } function saveBeforeExit() { show_confirm(); } function show_confirm() { var result=confirm("Do you want to save the changes before navigating."); if (result==true) { document.getElementById('hGridStateModified').value='YES'; return true; } else { document.getElementById('hGridStateModified').value='NO'; return true; } } ///END Thanks in advance. Best Regards, Sandip I need to have an online submission form, which accepts text for print adverts. Here is my problem: Whereas with Twitter, you are limited to 140 characters as the output is digital, with print the overall width of text is vital if it has to fit within a given space. Are there any javascript software libraries available that can calculate the printed length? Preferably as the user types. This assumes that the font, font-size and kerning are known. (I do not want to use the 'Courier' font) We will have to write this in-house unless there is something available on the internets (I'm possibly not the first person to come up against this) Can anyone help? (I've posted this at 'graphicdesignforum' but figure the readership will be different) Hi guys, Been stuck for a few days with this scenario. Any help? The alert box appears on an error. But the submitting won't stop. The details are submitted and the form is processed. Any help is greatly appreciated... Code: <html> <head> <script type="text/javascript" src="email_helper/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ // General options mode : "textareas", theme : "simple" }); </script> <script language="javascript"> function MM_openBrWindow(theURL,winName,features) { window.open(theURL,winName,features); } function err_check(){ var email = document.getElementById('to_email').value; if(email.length==0){ alert('Please Enter Email Address'); return false; } var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } email = document.getElementById('cc_email').value; if(email.length != 0){ var AtPos = email.indexOf("@") var StopPos = email.lastIndexOf(".") if (AtPos == -1 || StopPos == -1) { alert("Please Enter Valid Email Address"); document.getElementById('email').focus(); return false; } } var answer = confirm ("Send E-Mail?"); if (!answer){ return false; } } </script> <!-- /TinyMCE --> <style type="text/css"> body, table, td, th{ background-color:#CCCCCC; font-family: Arial; font-size:14px; } .que{ font-weight:bold; } </style> </head> <body> <form method="post" enctype="multipart/form-data"> <?php include 'library/database.php'; include 'library/opendb.php'; $query = mysql_query("SELECT email,contact,mobile FROM users WHERE user_id='$uid'") or die(mysql_error()); $row = mysql_fetch_row($query); $from_email = $row[0]; $from_person = $row[1]; $from_mobile = $row[2]; $query = mysql_query("SELECT customer_id FROM campaign_summary WHERE camp_id='$camp_id'") or die(mysql_error()); $row = mysql_fetch_row($query); $cusid = $row[0]; $query = mysql_query("SELECT email FROM client_info WHERE comp_id='$cusid'") or die(mysql_error()); $row = mysql_fetch_row($query); $toer = $row[0]; include 'library/closedb.php'; ?> <table width="100%" border="0"> <tr><td rowspan="4"><input type="submit" name="send_email" id="send_email" style="height:50px; width:100px;" value="SEND" onClick="return err_check();" /></td><td><span class="que">From : </span></td><td colspan="3"><?php echo $from_email; ?><input type="hidden" name="from_mail" id="from_mail" /><input type="hidden" name="camp_id" id="camp_id" value="<?php echo $camp_id;?>"/></td></tr> <tr><td><span class="que">To : </span></td><td colspan="3"><input name="to_email" id="to_email" style="width:250px;" value="<?php echo $toer;?>"/></td></tr> <tr><td><span class="que">CC : </span></td><td colspan="3"><input name="cc_email" id="cc_email" style="width:250px;"/></td></tr> <tr><td><span class="que">Subject : </span></td><td colspan="3"><input style="width:300px;" name="subject" id="subject" /></td></tr> <tr><td rowspan="1" colspan="2"> </td><td><input type="checkbox" name="ori_pdf" id="ori_pdf" checked /> PDF Quotation</td><td> </td><td> </td></tr><tr><td colspan="2"><span class="que">Credit Application</span></td><td><input type="checkbox" name="corporate" id="corporate"/>Corporate</td><td><input type="checkbox" name="individual" id="individual" />Individual</td><td><input type="checkbox" name="cash" id="cash" />Cash Account</td> </tr> <tr> <td colspan="2" rowspan="3"></td><td><input type="checkbox" name="tabloid" id="tabloid" />Tabloid Example</td> <td><input type="checkbox" name="broadsheet" id="broadsheet" />Broadsheet Example</td></tr> <tr><td><input type="checkbox" name="colmt" id="colmt" />Column Sizes Tabloid</td> <td><input type="checkbox" name="colmb" id="colmb" />Column Sizes Broadsheet</td></tr> <tr><td><input type="checkbox" name="maps" id="maps" />Maps / Distribution</td><td colspan="2" align="right">External Attachments <input id="upload_file" name="upload_file" type="file"/> </td></tr> <tr><td colspan="2"><span class="que">Message :</span></td><td colspan="3"> <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 100%"> <?php echo "<br><br><br>" . $from_person . "<br>" . $from_mobile; ?> </textarea> </td></tr> </table> </form> </body> </html> Greetings I have a textarea on my page and I wonder if its possible for a visitor to type in something in the textarea and then it will store in XML is it possible? Best Regards Obsivus Hi, The following code is supposed to display and hide fields when clicking on radio buttons which is does correctly, it also gives the fields that are hidden a value so that it passes validation. T The problem is that when the user moves from one field to the next, it deletes the value that they have just entered. :S Any ideas why this might occur? Thanks! Code: <script language="javascript" type="text/javascript"> function showHideDivs(){ var category = ''; for(i=0; i < oRadBtns.length; i++){ if(oRadBtns[i].checked){ category = oRadBtns[i].value; } } switch (category){ case 'empresa': document.getElementById("empresa_nombre").value = ""; document.getElementById("contacto").value = ""; document.getElementById("nombre").style.display = "none"; document.getElementById("apellido").style.display = "none"; document.getElementById("company").style.display = "block"; document.getElementById("contact").style.display = "block"; document.getElementById("firstname").value = "nombre"; document.getElementById("lastname").value = "apellido"; break; case 'particular': document.getElementById("firstname").value = ""; document.getElementById("lastname").value = ""; document.getElementById("nombre").style.display = "block"; document.getElementById("apellido").style.display = "block"; document.getElementById("company").style.display = "none"; document.getElementById("contact").style.display = "none"; document.getElementById("empresa_nombre").value = "empresa"; document.getElementById("contacto").value = "contacto"; break; } } window.onload=function(){ oRadBtns = document.getElementById('dmsfrm').getElementsByTagName('input'); for(i=0; i < oRadBtns.length; i++){ oRadBtns[i].onclick = showHideDivs; } showHideDivs(); } </script> Code: <div class="radio_element"> <input type="radio" value="empresa" class="radio" id="empresa" name="categoria" <?php echo ($leadsEngine->getElementValue('categoria')!='particular')?'checked="checked"':'' ?> /> <span class="<?PHP if($leadsEngine->hasError('categoria')){echo 'error';} ?> ">Empresa</span> </div> <div class="radio_element"> <input type="radio" value="particular" class="radio" id="particular" name="categoria" <?php echo ($leadsEngine->getElementValue('categoria')=='particular')?'checked="checked"':'' ?> /> <span class="<?PHP if($leadsEngine->hasError('categoria')){echo 'error';} ?> ">Particular</span> </div> </div> Hi, I have a form where dob is generated using 3 select boxes, 1 for day, month and year. My output needs to be in the form dob=dd-mm-yyyy rather than day=dd, month=mm and year=yyyy. It has been suggested that i do the following: "On submit button click, use JS to create a hidden input (Q5) in the form and assign its value, then disable the day, month, and year fields so they are not submitted." Does anyone know how to do this? I have 4 text boxes that are supposed to load 4 seperate values of data from one field in one table from a database. The field is called interface_cropsettings (from the interface table) and these values have been concatenated and comma seperated in this field. Code: <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceXPosition" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceYPosition" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceCropHeight" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceCropWidth" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> Once the form is filled out and saved, the data is inserted into the database and the values from these 4 text boxes are concatenated, comma seperated and inserted into that one field correctly. (Example) If the 4 text boxes have the following values: X Position = 12.34 Y Position = 56.78 Crop Height = 250 Crop Width = 500 in the database field they become: 12.34,56.78,250,500 However, if the form is closed and then re-opened, each text box displays the entire database field rather then each value seperated in the corresponding text box. (Example) All 4 text boxes display this: 12.34,56.78,250,500 I already know why the data appears like this in the form, my problem is that I'm not sure how to write the javascript to seperate the values into the correct corresponding fields, assuming javascript is what I should be using! Can anyone help me out with this?? Also, this is kind of irrelevant but just in case you're wondering, this form is part of a cold fusion application! Hey all, Okay, Here is what i would like to do. I have a calculator he http://www.nico-online.co.uk/calculator/calc1.html which after some help from Dormilich - got working! Now, I would like to set up some conditions, so if the use selected 'Mountainbike' then, the script will perform a different calculation to if they select the 'Rennrad' option. Okay, so I was thinking an If..else..if..else statement would probably be best after reading up This is what I have come up with: Code: <script language="JavaScript"> function Framesize() { var a = parseFloat(BikeSizer.Insleg.value); if(BikeSizer.Biketype.value = "Mountainbike") { b = (a * 0.572); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 0.226); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } else if (BikeSizer.Biketype.value = "Trekking-, Reise- oder Cityrad") { b = (a * 5); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 5); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } else{ b = (a * 10); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 10); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } } </script> So, I'm not too sure if I can set the Menu values as recongnisable values! Here are the values I have: <select name="Biketype" style="font-size:11px;"> <option>Mountainbike</option> <option>Trekking-, Reise- oder Cityrad</option> <option>Rennrad</option> </select> Anyone out there offer any insight? Am I going horribly wrong somewhere? Apologies for the stupidness , I am quite new to JS! Thanks in advance Hi, I'm having a bit of trouble with this here... Before I submit the form with JS I update an input field with js like this: Code: Code: document.getElementById('IC_Checksum').value = data; imaginaryform.submit(); The problem is that the updated value is not sent along with the post data. Instead the old value is sent along. When i submit the form with a button afterwards though (not auto submit after the value is set), then the value is sent along fine. But that's not how I want it to work... Can anyone tell me how I can send the value that I'm setting with JS along with the post data like this? I have a JQuery autosuggest working properly on my form.php page... Now I want to get my form to actual POST the input values. So currently if I just run search.php, I get the following (using echo json_encode): {"label":"Henry Gale","value":"henrygale@gmail.com"},{"label":"Amy Gerges","value":"amy@yahoo.com"}, and the list goes on. So since the search is working properly. Now, I want to POST only the values that I place in the form's input field. I currently have: Code: <script> $(document).ready(function() { $( "#autocomp" ).autoSuggest("search.php", { minChars: 2, selectedItemProp: "label", searchObjProps: "label", selectedValuesProp: "value", selectionLimit: 8, formatList: function(data, elem){ var my_image = data.image ; var my_label = data.label; var new_elem = elem.html(my_image + my_label); return new_elem; } }); }); </script> <input name="contacts" type="text" id="autocomp" maxlength="35" /> But if I do an echo of the $_POST['contacts'] I just get the word: Array I am doing something wrong, just not sure what... Since my input gets a list of comma separated values, how can I: 1) make sure the input values get the "value" attribute which corresponds to the emails. 2) post the emails so I can do things with the emails (run them through format checks, insert them into a mysql db, etc). Hello, I have a form that works out some basic math questions e.g. area etc. I run a function when a form field is updated to do the calculations, however I'd like to run a different calculation depending on which form element was updated. Is there a way to say something like: if (area1 was updated) { work out this calculation } if(area2 was updated) { work out this calculation } and so on? Thanks, Nicola I'm trying to add the ui autocomplete function to some form fields using a facebook style, but I'm not sure how to get more than one value to actually pass to the form field. As my script is now it only takes the last selected value into the hidden form field. Here's my current script: Code: <div id="editcbprofileinterests"> <div id="formWrap"> <div id="interests" class="ui-helper-clearfix"> <input id="cb_intereststerm" type="text"> <input id="cb_interests" name="cb_interests" type="hidden"> </div> </div></div> <script type="text/javascript" src="autocomplete/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="autocomplete/js/jquery-ui-1.8.custom.min.js"></script> <script type="text/javascript"> $(function(){ //attach autocomplete $("#cb_intereststerm").autocomplete({ //define callback to format results source: function(req, add){ //pass request to server $.getJSON("autocomplete/autocominterests.php?callback=?", req, function(data) { //create array for response objects var suggestions = []; //process response $.each(data, function(i, val){ suggestions.push(val.cb_intereststerm); }); //pass array to callback add(suggestions); }); }, //define select handler select: function(event, ui) { //create formatted interest var interest = ui.item.value, span = $("<span>").text(interest), a = $("<a>").addClass("remove").attr({ href: "javascript:", title: "Remove " + interest }).text("x").appendTo(span); //add interest to interests div span.insertBefore("#cb_intereststerm"); //add interest to hidden form field $('input[name=cb_interests]').val(interest); }, //define select handler change: function() { //prevent 'to' field being updated and correct position $("#cb_intereststerm").val("").css("top", 2); } }); //add click handler to activities div $("#interests").click(function(){ //focus 'to' field $("#cb_intereststerm").focus(); }); //add live handler for clicks on remove links $(".remove", document.getElementById("interest")).live("click", function(){ //remove current activity $(this).parent().remove(); //correct 'to' field position if($("#interests span").length === 0) { $("#cb_intereststerm").css("top", 0); } }); }); </script> I am having some trouble trying to fix my math equation to calculate the total rent by aquiring values from my form fields. Converting the date fields to days and finding the number of days via two date fields is mainly where I am having trouble. Also, I am trying to have a window pop up before submission but the onclick event does not seem to function properly. Any suggestions would be greatly appreciated. Thank you. Below is the math equation I have come up with: Code: //calculate days from date field function calcTotal(date1, date2) { //assign variables var equip = parseFloat(document.forms[0].equipment.value) var pDate = parseFloat(document.forms[0].pickupDate.value) var pHours = parseFloat(document.forms[0].pickupHours.value) var pMinutes = parseFloat(document.forms[0].pickupMinutes.value) var rDate = parseFloat(document.forms[0].returnDate.value) var rHours = parseFloat(document.forms[0].returnHours.value) var rMinutes = parseFloat(document.forms[0].returnMinutes.value) // The number of milliseconds in one day var ONE_DAY = 1000 * 60 * 60 * 24 // Convert both dates to milliseconds var date1_ms = rDate.getTime() var date2_ms = pDate.getTime() // Calculate the difference in milliseconds var difference_ms = Math.abs(date1_ms - date2_ms) //calculate total cost and diplay in window.confirm() dialog box var pTime = pHours + pMinutes; var rTime = rHours + rMinutes; var total = (((difference_ms/ONE_DAY) - 1) * 24) * equip + ((rTime + (24 - pTime)) * equip); var OK = window.confirm(" The total rental cost is $" + total + "\n Click OK to accept, Cancel to decline"); if (OK) {return true} else {return false} } Below is the body section of the form: Code: <input type = "submit" name = "submit" value = "Submit Reservation" onclick = "calcTotal()"/> Can someone help me I am trying to get these two values, firstname and lastname to both go into the same output box on a form. I want them to show up alongside one another like so nameform.output2.value=firstname + " " + lastname; but the values are assigned within seperate if statements as you can see below.. so I dont know how to get them to merge.. I am kinda new with javascript so any help will be very useful. Thakns very much. Code: function checkform(nameform){ var firstname=new Array(); firstname[0]="johndefinition"; firstname[1]="jamesdefinition"; var lastname=new Array(); lastname[0]="smithdefinition"; lastname[1]="simpsondefinition"; if (document.getElementById("namebox").value.indexOf("John")!=-1) {nameform.output2.value= firstname[0];} if (document.getElementById("namebox").value.indexOf("James")!=-1) {nameform.output2.value= firstname[1];} if (document.getElementById("namebox").value.indexOf("Smith")!=-1) {nameform.output2.value=lastname[0];} if (document.getElementById("namebox").value.indexOf("Simpson")!=-1) {nameform.output2.value=lastname[1];} } I want to loop through a form containing various fields and replace them with values I have in a JS object. E.g. (1) <form id="theform"> <input type="text" name="field_1" value="" /> <input type="checkbox" name="field_2" value="" /> </form (2) object.field_1 = "Dave"; object.field_2 = ""; // empty as not checked, else holds value of checked one -- The problem is: what about checkboxes and <select> drop downs, and radios?? Is there a script like this around as I'm guessing this could be useful for Ajax to populate input boxes in some situations (depending on the content etc.) so I'm guessing I'm not the only one who needs this? |