JavaScript - Stop My Form If A Field Is Empty
Hi. I have a form and if a field is blank a message pops up. This doesnt stop my php from running though and takes the user to another page.
Is there a line to keep them on that page untill all fields are filled out? code so far is simple. <script type="text/javascript" language="JavaScript"> function nameempty() { if ( document.form.subject1.value == '' ) { alert('No name was entered!') return false; } } </script> //then down the bottom I have a small bit that implements that code Similar Tutorialshiiii, im new to javascripts . Can anyone help me to know that a javascript which is validating a phone number accepts only digits but if the text field is left empty it should accept the entry as an empty entry.... plz share knowledge u will be more knowledgeable Hi. I have a form and in the form is a checkbox use as a switch to hide and unhide a two textbox. When the other textbox is hide, the other is unhide such as the code below. When the user click the submit button on the first time and there is an error, it reloads and the id="fieldset.-in_honor" hide because it is set to hide initially but not empty. My problem is, I want to show the fieldset whichever is not empty after submit button is click and there is an error so user will not enter any more information to the other field. Is that possible? Please help. I have a hard time explaining it but hopefully you will get the idea. Thanks in advance and hope to hear from you as soon as possible. Code: /*toggle switch*/ <p><input type="checkbox" name="in_honor" value="" id="checkmemoriam" onclick="showHide(this.name);" />Please check to make this donation in honor of someone special.</p> /*hide textbox but unhide when the switch is on or the checbox is check*/ <fieldset id="fieldset-in_honor" class="fieldgroup" style="display:none"> <legend class="hide">In Honor Of</legend> <p>To make this donation in honor of someone special, please complete the two fields below:</p> <div class="formfield" <?php echo highlight('donate_honor_name'); ?>> <label for="donate_honor_name">Name:</label> <input id="donate_honor_name" name="donate_honor_name" class="text" type="text" value="<?php safeEcho($form['donate_honor_name'])?>" /> <?php helper_error('donate_honor_name'); ?> </div> <div class="formfield" <?php echo highlight('donate_honor_acknowledgement'); ?>> <label for="donate_honor_acknowledgement">Acknowledgement should be sent to:</label> <textarea id="donate_honor_acknowledgement" name="donate_honor_acknowledgement"><?php safeEcho($form['donate_honor_acknowledgement'])?></textarea> <?php helper_error('donate_honor_acknowledgement'); ?> </div> /*always show on first load of the page but once the checkbox is check, will need to hide and delete info entered*/ <fieldset id="fieldset-in_registration"> <label for="impact" style="font-weight:bold">B. Impact Areas</label> <table> <tr> <td style="width:380px;text-align:left"><label for="d" id="deslist4" name="deslist4">Crime and Drug Use <a href="javascript:alert('Ensuring prevention and treatment programs and appropriate support services are available to people who are at risk for drug addiction and supporting efforts to reduce crime.');">what is this?</a></label></td> <td style="float:right"> $<input id="d" name="d" class="text" type="text" value="<?php safeEcho($form['d'])?>" style="width:90px;" onChange="CalculateTotal()" /> <?php helper_error('d');?> </td> </tr> <tr> <td style="width:380px;text-align:left"><label for="e" id="deslist5" name="deslist5">Early Childhood Development <a href="javascript:alert('Children are healthy, loved, nurtured, safe and have access to quality childcare and early education. This includes programs that increase parenting skills, providing books to all children and providing developmental screening for 3 and 4 year olds.');">what is this?</a></label></td> <td style="float:right"> $<input id="e" name="e" class="text" type="text" value="<?php safeEcho($form['e'])?>" style="width:90px;" onChange="CalculateTotal()" /> <?php helper_error('e');?> </td> </tr></table> Code: /*JAVASCRIPT FUNCTION*/ function showHide() { if (document.getElementById('checkmemoriam').checked) { if (document.getElementById('TotalC').value == "0.00") { document.getElementById('fieldset-in_honor').style.display=""; // this is for showing document.getElementById('fieldset-in_registration').style.display="none"; } else { var answer = confirm("You entered a total gift designation of $" + document.getElementById('TotalC').value + ". At this time, gifts made \"in honor of someone special\" are not eligible for the designation option. Clicking the OK button will delete all your designation(s). Do you want to continue?") if (answer) { document.getElementById('TotalC').value="0.00"; document.getElementById('d').value="0"; document.getElementById('e').value="0"; document.getElementById('fieldset-in_honor').style.display=""; // this is for hiding document.getElementById('fieldset-in_registration').style.display="none"; } else { document.getElementById('checkmemoriam').checked=false; } } } else { if ((document.getElementById('donate_honor_name').value="") && (document.getElementById('donate_honor_acknowledgement').value="")) { document.getElementById('fieldset-in_honor').style.display="none"; // this is for hiding document.getElementById('fieldset-in_registration').style.display=""; } else { var answer = confirm("The field you are trying to close will delete all information you entered \"in honor of someone special\" but it will allow you to designate. Clicking the OK button will show the designation list. Do you still want to continue?") if (answer) { document.getElementById('donate_honor_name').value = ""; document.getElementById('donate_honor_acknowledgement').value = ""; document.getElementById('fieldset-in_honor').style.display="none"; // this is for hiding document.getElementById('fieldset-in_registration').style.display=""; } else { document.getElementById('checkmemoriam').checked=false; document.getElementById('fieldset-in_honor').style.display=""; // this is for showing document.getElementById('fieldset-in_registration').style.display="none"; } } } } HI I have a form that has some fields and inputs . I wrote some javascript code that if there was any problem with entered values , it shows the errors but when the user press submit button , the form submited before it had shown the problems . How can halt it and showing the problems ? TNX I am very new to javascript and cannot find any info anywhere regarding the following problem: On my website I have around 100 pages containing an action form. Occasionally it is necessary to cancel the action throughout the 100 pages which is very time-consuming. Then the action has to be reinstated once again for all the 100+ pages. I thought the solution would be to use javascript to change the action from a .js file which would mean only one page, the .js file, would require alteration: The action that appears on all 100+ pages several times that I am trying to change or stop happening by overwriting the "form action": <form action="http://www.changenamecart.com/" method="post"> <input type="hidden" name="userid" value="1234567"> <input type="hidden" name="return" value="http://www.thehomepage.co.uk/index.htm"> <input type="image" src="http://www.changenamecart.com/images/pic.gif"> </form> My efforts to date a The change .js file: function change() { var myChange = form action; if(myChange == form action){ document.write("form xction"); } } The html file in the header: <script src="change.js" type="text/javascript"></script> I am afraid that my knowledge of programming is very small and I would welcome any help to solve this problem. I have created a small file where I check if the passwords entered in the code match or not, if they do not match, the button that links to the next webpage should not work(allow them to go to the next wepage). ive tried various websites to help me try and solve this but I just dodont understand what they are doing. I'm very new to programming btw here is some example code: Code: !doctypeHTML <html> <script> //lets just pretend that ive already done all the .getelement by id stuff to get the code things //suppose the person did not write anything in the form, an error will get pushed(alerted basically) if(!form['password'].value) error.push('Missing Password'); <form> <label>Password<br><input type="password" name="password"></label> <label>Confirm Password<br><input type="password" name="confirm"</label> </form> </html> now how would I make the submit button not submit if there are errors? please be as simple as possible, I am new to this! Is there a way to stop a form submit after hitting submit? Refresh wouldn't realy be an option. Is abort() what I'm looking for?
Hi guys im trying to give users a warning message with javascript when the submit my login form without inserting any new data. But I can't seem to find out how to stop the form from going to the login.php here is my code. Code: <form name="te" onsubmit='login();' action='login.php' method='post'> <input name='username' maxlength='14' value='Username' type='text' /> <input name='password' maxlength='20' value='Password' type='password' /> <input type="submit" name="login" value="Login" /> </form> javascript: Code: <script type="text/javascript"> function login() { var username = document.te.username.value; var password = document.te.password.value; if (username == 'Username' || username == '') { alert('empty username!'); return false; } else { if (password == 'Password' || password == '') { alert('empty pass'); return false; } } return true; } </script> hi dears, I'm trying to do simple form validation. But the form submits right after validated! at FireFox only. as i tried it at IE it works fine. condition: if return false the event must be stop, killed submitting the form value's. my form is: Code: <form action="index.php" id="cat_form" method="post" name="cat_form" onsubmit="return cats();"> my js is: Code: function cats() { if (document.cat_form.txttitle.value=="") { alert ("Sorry, Don't keep it blank!!") cat_form.txttitle.focus(); return false; } else if (document.farticle.txtperpg.value==0) { alert("Sorry, Value must be grater than Zero"); cat_form.txtperpg.focus(); return false; } else { return true; } } Any Idea ? I've set up a mock registration form page so I can learn a bit about javascript's form validation. (newbie) I want to try to attempt to style the border of a form field green when the user enters the correct info into the form text field and red on all other fields if the user doesnt enter any info into them. When i test it, enter the right info into the username field, leave the others blank, and hit the submit button it styles the username field green ok but it doesnt make the next fields (password and so on) red. Could someone please explain what I am doing wrong? here is my code so far... Note: just for testing purposes I've put return false on everything so it displays a message when everythings ok. Code: .... <script type="text/javascript"> window.onload = function() { document.forms[0].username.focus(); } function validate(form) { var form = document.getElementById("reg"); var e = document.getElementById("error"); e.style.background = "red"; for(var i = 0; i < form.elements.length; i++) { var el = form.elements[i]; if(el.type == "text" || el.type == "password") { if(el.value == "") { e.innerHTML = "Please fill in all fields!"; el.style.border = "1px solid red"; el.focus(); return false; } else { el.style.border = "1px solid green"; return false; } } } var un = form.username; un.value = un.value.replace(/^\s+|\s+$/g,""); if((un.value.length < 3)|| (/[^a-z0-9\_]/gi.test(un.value))) { e.innerHTML = "Only letters,numbers and the underscore are allowed (no spaces) - 3-16 characters"; un.focus(); return false; } var pw = form.password; pw.value = pw.value.replace(/^\s+|\s+$/g,""); if((pw.value.length < 3) || (/[^a-z0-9]/gi.test(pw.value))) { e.innerHTML = "Only letters and numbers are allowed (no spaces) - 3-16 characters"; pw.focus(); return false; } e.innerHTML = "You filled in all the fields, well done!"; e.style.background = "green"; return false; } </script> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Cool Website</h1> </div> <div id="content"> <div class="padding"> <h2>Registration</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc vitae purus. Aenean viverra malesuada libero. Fusce ac quam. Donec neque. Nunc venenatis enim nec quam. Cras faucibus, justo vel accumsan aliquam, tellus dui fringilla quam, in condimentum augue lorem non tellus. Pellentesque id arcu non sem placerat iaculis. Curabitur posuere, pede vitae lacinia accumsan, enim nibh elementum orci, ut volutpat eros sapien nec sapien. Suspendisse neque arcu, ultrices commodo, pellentesque sit amet, ultricies ut, ipsum. Mauris et eros eget erat dapibus mollis. Mauris laoreet posuere odio. Nam ipsum ligula, ullamcorper eu, fringilla at, lacinia ut, augue. Nullam nunc.</p> <form id="reg" action="#" method="post" onsubmit="return validate(this)"> <div id="error"></div> <div><label for="username">Username</label></div> <div><input type="text" name="username" id="username" size="30" maxlength="16" /></div> <div><label for="password">Password</label></div> <div><input type="password" name="password" id="password" size="30" maxlength="16" /></div> <div><label for="c_password">Confirm Password</label></div> <div><input type="password" name="c_password" id="c_password" size="30" maxlength="16" /></div> <div><label for="email">Email address</label></div> <div><input type="text" name="email" id="email" size="30" maxlength="200" /></div> <div><label for="c_email">Confirm Email address</label></div> <div><input type="text" name="c_email" id="c_email" size="30" maxlength="200" /></div> <div><label for="firstname">First name</label></div> <div><input type="text" name="firstname" id="firstname" size="30" maxlength="100" /></div> <div><label for="surname">Surname</label></div> <div><input type="text" name="surname" id="surname" size="30" maxlength="100" /></div> <div><label for="gender">Gender</label></div> <div> <div><input type="radio" name="gender" id="gender" value="m" checked="checked" />Male</div> <div><input type="radio" name="gender" value="f" />Female</div> </div> <div><input type="submit" value="Register" name="submit" /></div> </form> </div> </div> <div id="footer"> <p>Copyright © 2009 My Cool Website</p> </div> </div> </body> </html> Hey guys, I'm working on a user website and have got the upload form working and the cropping working, also got the image in my profile, all works great. A few things I need tho and wondering if you could help. I need to stop the form from resubmitting the image when I refresh the upload.php page below upload.php PHP Code: <?php define('INCLUDE_CHECK',true); require 'connect.php'; session_start(); $session_id ='1'; $username = $_SESSION['user']; $upload = $_POST['upload']; $new_name = "small".$username.".jpg"; $path = "uploads/"; ?> <html> <head> <title>My Network</title> </head> <link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" /> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.imgareaselect.pack.js"></script> <script type="text/javascript"> function getSizes(im,obj) { var x_axis = obj.x1; var x2_axis = obj.x2; var y_axis = obj.y1; var y2_axis = obj.y2; var thumb_width = obj.width; var thumb_height = obj.height; if(thumb_width > 0) { if(confirm("Do you want to save image..!")) { $.ajax({ type:"GET", url:"ajax_image.php?t=ajax&img="+$("#image_name").val()+"&w="+thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis, cache:false, success:function(rsponse) { $("#cropimage").hide(); $("#thumbs").html(""); $("#thumbs").html("<img src='uploads/"+rsponse+"' />"); } }); } } else alert("Please select portion..!"); } $(document).ready(function () { $('img#photo').imgAreaSelect({ aspectRatio: '1:1', onSelectEnd: getSizes }); }); </script> <?php $valid_formats = array("jpg", "png", "gif", "bmp"); if(isset($_POST['submit'])) { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats) && $size<(1024*1024)) { $actual_image_name = time().substr($txt, 5).".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { mysql_query("UPDATE user SET profile_image='$actual_image_name' WHERE id='$username'"); $image="<h1>Please drag on the image</h1><img src='uploads/".$actual_image_name."' id=\"photo\" style='max-width:500px' >"; $profile_image="<img src='uploads/".$new_name."' style='max-width:500px' >"; } else echo "failed"; } else echo "Invalid file formats..!"; } else echo "Please select image..!"; } ?> <body> <div style="margin:0 auto; width:600px"> <?php echo $image; ?> <div style="padding:5px; width:600px"> <?php echo $profile_image; ?> </div> <div style="width:600px"> <form id="cropimage" method="post" enctype="multipart/form-data"> Upload your image <input type="file" name="photoimg" id="photoimg" /> <input type="hidden" name="image_name" id="image_name" value="<?php echo($actual_image_name)?>" /> <input type="submit" name="submit" value="Submit" /> </form> </div> </div> </body> </html> ajax_image.php PHP Code: <?php define('INCLUDE_CHECK',true); require 'connect.php'; session_start(); $username = $_SESSION['user']; $upload = $_POST['upload']; $t_width = 100; // Maximum thumbnail width $t_height = 100; // Maximum thumbnail height $new_name = "small".$username.".jpg"; // Thumbnail image name $path = "uploads/"; if(isset($_GET['t']) and $_GET['t'] == "ajax") { extract($_GET); $ratio = ($t_width/$w); $nw = ceil($w * $ratio); $nh = ceil($h * $ratio); $nimg = imagecreatetruecolor($nw,$nh); $im_src = imagecreatefromjpeg($path.$img); imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w,$h); imagejpeg($nimg,$path.$new_name,90); mysql_query("UPDATE user SET profile_image_small='$new_name' WHERE username='$username'"); echo $new_name."?".time(); exit; } ?> And I also need a live preview of cropping. So when the user is selecting what area of the Large image they want as there final thumb image, they can see the thumb change to that selection at the same time. The thumb is below the uploaded image, and without refreshing, which I cannot yet do because of the form resubmit, you can't see the final image until you go back to your profile. If I didn't make the above clear enough, please tell me. Thanks for any help and suggestions. How can I add a form field value to a url. I tried the below but it no work. Code: href="index2.php?q=4&id=+document.theForm.lists.value+&picklist" Is there a way to give an input or textarea field the focus and set the focus to begin right at the end of the current text in the field?
function checkValidFormInput() { if (document.getElementsByName('customerName').value != '') { document.getElementById('customerNameImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerNameImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } if (document.getElementsByName('customerEmail').length > 0) { document.getElementById('customerEmailImg').innerHTML = '<img alt="Valid" src="images/greenTick.png">'; } else { document.getElementById('customerEmailImg').innerHTML = '<img alt="Invalid" src="images/redX.png">'; } } I have a form which has various fields which are arrays (so the name of a field may be myField[]). The reason for this is that the form has add buttons to add another field or fields for the purpose of entering another email address, etc., to send invitations and do other things. The problem that I am running into is how to access the individual fields in an array of fields inside javascript to do form validation. So if I have an email address field name emailAddress[], and using the add button, the user of my site adds 3 other copies of the emailAddress[] field, I want to then do form validation onSubmit to ensure those email address are valid using standard procedures. However, inside the javascript code, how do I access the individual fields that make up emailAddress[]? I just cannot find anywhere online the proper way to get at these values. If anyone can help me, I would greatly appreciate it. Happy Holidays Hi! I use the :: Form field Progress Bar from DynamicDrive: Form field Progress Bar Now I trided to change the text when the textarea is full "Limit:100%" to "Your max. characters is reached" I trided it but with no luck. This is the main code.. Code: <script type="text/JavaScript"> function textCounter1(field,counter,maxlimit,linecounter) { // text width// var fieldWidth = 137; var charcnt = field.value.length; // trim the extra text if (charcnt > maxlimit) { field.value = field.value.substring(0, maxlimit); } else { // progress bar percentage var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ; document.getElementById(counter).style.width = parseInt((fieldWidth*percentage)/100)+"px"; document.getElementById(counter).innerHTML="Limiet: "+percentage+"%" // color correction on style from CCFFF -> CC0000 setcolor(document.getElementById(counter),percentage,"background-color"); } } function setcolor(obj,percentage,prop){ obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)"; } </script> This is the place where the text is set. Code: ((fieldWidth*percentage)/100)+"px"; document.getElementById(counter).innerHTML="Limiet: "+percentage+"%" Help would be highly appreciated ! greetings Jardin Hi there, I have a html form, and I need it so that when a user clicks a button, it adds a field into the form. I also need it to write <td></td> around the new field, and I need it to write this in a specific part row of a table. How would I go about doing this? I've tried searching for the past two hours, but no luck. Many thanks, I appreciate it, Jason I need to learn how to clear form fields when a user clicks on them. Here is the site in question: http://www.yourvancouvermortgagebroker.ca/apply They used to work, but then I changed the field value and now it doesn't work on some of the fields (whichever ones I changed). Here is a link to the .js file: http://www.yourvancouvermortgagebroker.ca/js/apply.js I need help troubleshooting javascript I am using to concatenate two fields in a form and populating a hidden field with them. Here's the javascript: <script type="text/javascript"> function combName() { var fname = document.forms[0].fname.value; var lname = document.forms[0].lname.value; document.forms[0].name.value = fname + " " lname; } </script> Here are the form fields: <input id="fname" name="fname" type="text"> <input id="lname" name="lname" type="text" onKeyUp="combName()"> <input name="name" type="hidden" id="name" size="20" maxlength="80"> <input name="Submit" type="submit" id="OnSubmit" value="OnSubmit"> What am I doing wrong? Thanks. |