I tried to create a function to check on a drop-down option on select box. It requires a user to select a user name before submit. I put '0' and check if this = 0, then return false, but it didn't work.
I added a function to check radio buttons and they all worked fine. However, the select Staff doesn't work. I mean, when I click on Submit after checking all radio boxes, it get submitted anyway. How do I fix it to make it work?
Can you help me?
<script language="javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a user");
return false
}
// add other checks here...
alert ("Thank you!")
window.open("Search.asp")
return true
}
<body>
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
<select name="UserID">
<option value=0>Staff name:</option>
<option value=1>Jenny</option>
<option value=2>David</option>
</select>
<input type="submit" value="Submit">
</form>
Thank you very much!
It looks like something is wrong with the selector.
Comparing against a "0" value seems to work just fine. I've included a snippet which shows this.
In short, change this...
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a staff");
return false
}
To this
if (document.querySelector("[name='UserID']").value == 0) {
alert("Please select a staff");
return false
}
Make multiple selections and submit to see the results.
function validateForm(daForm){
var select = document.querySelector("[name='UserID']")
if(select.value == 0){
console.log("Please select a value");
}else{
console.log("Selection made.");
}
return false;
}
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
<select name="UserID">
<option value=0>Staff name:</option>
<option value=1>Jenny</option>
<option value=2>David</option>
</select>
<input type="submit">
</form>
You cannot just use UserID and work on it with JavaScript. That is the name of the select element. What you need to do is to select it using JavaScript and then work with it.
var UserID = document.getElementsByName("UserID")[0];
if (UserID.options[UserID.selectedIndex].value == 0) {
alert("Please select a staff");
return false
}
// add other checks here...
alert ("Thank you!")
return true;
}
<== Fiddle Me ==>
Related
I have a form that has multiple elements/types
inputs for name, email, address, etc.
radio button for shipping speed.
select tags for "state" & "credit card type".
I want to disable the submit button until the:
1.inputs are filled out.
the select tags have an option selected
the radio is checked.
I've selected the elements (see below);
const btn = document.querySelector('#olegnax-osc-place-order-button');
let inputs = document.querySelectorAll('#olegnax-osc-billing-address-list .required-entry, input#authorizenet_cc_number');
let selectTags = document.querySelectorAll('#olegnax-osc-billing-address-list select, #payment_form_authorizenet select');
let radio = document.querySelector('#s_method_owebiashipping1_id_06');
My question is, being the form consists of 3 different types (input, select, radio), can I just create one array with all of these elements and loop though to make sure the value for each is not blank?
For example, say I store all the different elements in an array called "requiredFields" would this work?:
for (var i = 0; i < requiredFeilds.length; i++) {
if (requiredFeilds[i].value === '') {
btn.disabled = true;
}else {
btn.disabled = false;
}
}
There's a lot more to form validation than meets the eye, but that being said you have a major flaw in your logic. Namely, as you loop over all the fields, you could be changing btn.disabled back and forth depending on the value of the form field (or lack of a value).
Instead, begin with the button disabled, and then instead of looping, use Array.prototype.some (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to check if any field is missing a value, something such as:
btn.disabled = requiredFields.some(field => field === '');
There's lots else to address with regards to your approach but this corrects your current logic error and is much more concise.
You can loop through everything but the radio buttons easily. For the radio buttons, you want to check if any of the buttons in a radio group are checked, so it is a little more complicated. It might be easier to just designate a radio button as default, with the checked attribute:
document.querySelector("input[type=submit]").disabled = true;
const inputs = Array.prototype.slice.call(document.forms["form1"].querySelectorAll("input[type=text], select"));
document.forms["form1"].addEventListener("input", () => {
let complete = true;
inputs.forEach((field) => {
if(field.value.trim() === "") {
complete = false;
}
});
document.querySelector("input[type=submit]").disabled = !complete;
});
form{
display:flex;
flex-flow:column;
align-items:flex-start;
}
<form name="form1" id="form1">
<input type="text" name="bar" />
<input type="text" name="foo" />
<select name="biz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<select name="baz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<label>
A <input type="radio" name="buzz" value="a" checked />
</label>
<label>
B <input type="radio" name="buzz" value="b" />
</label>
<input type="submit" value="Submit" />
</form>
Yes, just combine your selectors and use a comma, and check tagName:
const requiredFields = document.querySelectorAll( "
#olegnax-osc-place-order-button,
#olegnax-osc-billing-address-list .required-entry,
input#authorizenet_cc_number,
#olegnax-osc-billing-address-list select,
#payment_form_authorizenet select,
#s_method_owebiashipping1_id_06
" );
for( let input of requiredFields ) {
if( input.tagName == "INPUT" ) {
}
else if( input.tagName == "SELECT" ) {
}
else if( input.tagName == "TEXTAREA" ) {
}
}
You should also use the required attribute too:
<input type="text" required />
<select required></select>
<textarea required></textarea>
I have working script which is sending emails from website to some array of emails.
Problem is: If the user forgot to choose value from select box (value = email to mail#mail.com in PHP array) my script is throwing alert "Choose a value!" but all data wrote by the user will be deleted from all select boxes.
Is there any way to avoid it?
JS:
function formSubmit() //onclick "Submit" button
{
var selectedValue = document.getElementById("sendTo").value;
if(selectedValue="99")
{
alert("Choose a value!");
}
else
{
//working ajax script which is sending emails
}
}
HTML:
<label class="company_emails">
<select id="sendTo">
<option value="99">Choose a department</option>
<option value="0">Justice</option>
<option value="1">Injustice</option>
<option value="2">Potatoes</option>
<option value="3">Mushrooms</option>
</select>
</label>
You have to stop the submit when there is an error, otherwise the form will be submitted and is empty again.
function formSubmit() {
var selectedValue = document.getElementById("sendTo").value;
if( selectedValue == "99" ) {
alert("Choose a value!");
// return false will stop the submit
return false;
}
}
But if you do it with onclick on a button you have to use return there too:
<button type="submit" onclick="return formSubmit();">send</button>
Or even better, if you have jQuery available, just register a listener on the form submit and use preventDefault. This is the best way imo.
$("form").on("submit", function(e) {
if( $("#sendTo").val() == "99" ) {
alert("Choose a value!");
// will stop the submit
e.preventDefault();
}
});
And as user #Carr said, you have missed a = in your if statement.
JavaScript code
<script type="text/javascript">
function formSubmit() //onclick "Submit" button
{
var selectedValue = document.getElementById("sendTo").value;
if(selectedValue="99")
{
alert("Choose a value!");
return false;
}
else
{
//working ajax script which is sending emails
}
}
</script>
And need to have return keyword on-click method of button as below.
<input type="submit" value="submit" onclick="return formSubmit()"/>
I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/
In the following code I am trying to get the select box to display a message beside the box if it hasn't selected a value of male or female. and not show it if it has one of these values selected. but it isnt working, it works fine with the text boses for email and password can anyone see why this isnt working and help me with the answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!-- saved from url=(0045)https://vle.wit.ie/file.php/8220/lab5pt2.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function validate_gender(field,alerttxt)
{
with (field){
apos=value.indexOf("0");
if (apos>0)
{
document.getElementById('gender_help').innerHTML="";
return true;
}else{
document.getElementById('gender_help').innerHTML=alerttxt;
return false;
}
}
}
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{document.getElementById('email_help').innerHTML=alerttxt;return false; }
else {document.getElementById('email_help').innerHTML="";return true;}
}
}
function validate_password(field, alerttxt){
with (field){
var re = /^[a-zA-Z0-9]{6,8}$/;
if (re.test(value))
{
document.getElementById('pass_help').innerHTML="";
return true;
}else{
document.getElementById('pass_help').innerHTML=alerttxt;
return false;
}
}
}
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (!validate_gender(gender,"A Valid gender is Required"))
{gender.focus();return false;}
if (!validate_email(email,"A Valid Email is Required"))
{email.focus();return false;}
if (!validate_password(pass,"Password must be between 6 and 8 characters and contain both numbers and alphas"))
{pass.focus();return false;}
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validate_form(this)" method="post">
What is your gender?<br />
<select name="gender" ><span id="gender_help"></span>
<option value="0" selected="selected">Select...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select><br/>
Email: <input type="text" name="email" size="30" ><span id="email_help"></span><br>
Password <input type="password" name="pass" size="30"><span id="pass_help"></span><br>
<input type="submit" value="Submit">
</form>
</body></html>
This is a shocking display of anti-patterns!!
Don't use with.
Cache your selectors i.e. var emailHelper = document.getElementById('email_help')
Don't use inline javascript i.e onClick=''
Consider using a library like jQuery to handle events in a cross-browser way.
Generally it's not good to put braces on a new line.
You shouldn't have a <span> inside of the <select> element.
Check out http://javascript.crockford.com/ or http://eloquentjavascript.net/ for some other tips and tricks and best practices. Also more about why not to use with here: Are there legitimate uses for JavaScript's "with" statement?
Now on to the actual question!
You're having trouble with the select box. Let's try something like this:
var genderHelper = document.getElementById('gender_help')
function validate_form(thisform) {
// your other stuff
if (!validate_gender(thisform.gender.value,"A Valid gender is Required")) {
thisform.gender.focus();
return false;
}
}
function validate_gender(gender, error) {
var validGender = (gender === "M" || gender === "F")
if (!validGender) {
genderHelper.innerHTML = error
}
return validGender
}
Update
After playing with it for while in jsFiddle I've found the problem appears to be that your <span> tag is nested within the <select> tag, which is why you can't see it.
Here's a working version mostly using your code:
http://jsfiddle.net/6buUJ/1/
You can not display text in a select area that is not an option or a optgroup.
I think it better to :
add a span with 'A Valid gender is Required' close to select area and display it, when gender is not select.
or border in red the select area if gender mising.
You can't nest a span inside a select element.
You could however update one of the select elements to have the text you want the user to see.
Probably just having the span next to the select is the best though.
This is not valid html:
<select name="gender" ><span id="gender_help"></span>
<option value="0" selected="selected">Select...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
"0".indexOf("0") is 0
"M".indexOf("0") is -1
"F".indexof("0") is -1
You could check if (value != '0') { return true; }
I'm working on a form validation script at work and am having some difficulty. The form is meant to make sure that the user fills out a name, a real-looking email, a category (fromt he drop down) and a question:
This names the form and gathers all the data up from the form:
<script>
function checkForm(form1) {
name = document.getElementById("FieldData0").value;
category = document.getElementById("FieldData3").value;
question = document.getElementById("FieldData1").value;
email = document.getElementById("FieldData2").value;
This checks to see that something is in the "name" field. It works fine and validates exactly like it should, displaying the error text:
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("FieldData0").select();
document.getElementById("FieldData0").focus();
return false;
This also works just like it should. It checks to see if the email field is empty and if it is empty,displays error text and selects that field:
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
This also works just like it should, makes sure that the questions field isn't empty:
else if (question == "") {
hideAllErrors();
document.getElementById("questionError").style.display = "inline";
document.getElementById("FieldData1").select();
document.getElementById("FieldData1").focus();
return false;
}
This one works partially - If no drop down is selected, it will display the error message, but that doesn't stop the form from submitting, it just displays the error text while the form submits:
else if (category == "") {
hideAllErrors();
document.getElementById("categoryError").style.display = "inline";
document.getElementById("FieldData3").select();
document.getElementById("FieldData3").focus();
return false;
}
This one doesn't work at all no matter where I put it. I used a variation on the same script last week and it worked fine. This is supposed to check to see that the email entered looks like a real email address:
else if (!check_email(document.getElementById("FieldData1").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
Otherwise it lets the form submit:
return true;
}
This checks the email out:
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
This function hides all errors so the user isn't bombarded with red text. I tried putting in "document.getElementById("emailError").style.display = "none"" but that breaks the whole thing:
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
</script>
And the form looks like this:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
<label for="name"></label></p>
<p><div class=error id=emailError>Required: Please enter your email address<br/></div>
<div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div>
<strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
<label for="email"></label>
</p>
<div class=error id=categoryError>Please select a category from the drop-down menu<br></div>
<p><strong>Category:</strong> <span></span><br>
<p><select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select><label for="category"></label>
<p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p>
<p><input type="submit" class="btn" value="Submit Question" name="Submit"></p>
</div>
</form>
Is the problem the order that I run the checks? I can't seem to figure this out. Any help would be appreciated.
I've taken the liberty to re-write your javascript to make it more readable and easier to debug.
As Marc Bernier mentioned, the dropdown element does not support the select function so I put an if statement around it to prevent an exception. I've also simplified your checkEmail function, it seemed rather convoluted. I renamed it to isAnInvalidEmail in order to make the checkForm code simpler.
You have also incorrectly named the 'emailError2' div in your HTML, which would cause another exception in the javascript. Your HTML is rather messy and, in some cases, invalid. There are missing quotes on some attribute values and missing end-tags. You should consider using the W3C validator to ensure your HTML is clean and is standards compliant.
I've hosted your code on jsbin: http://jsbin.com/iyeco (editable via http://jsbin.com/iyeco/edit)
Here's the cleaned up Javascript:
function checkForm() {
hideAllErrors();
var formIsValid =
showErrorAndFocusIf('FieldData0', isEmpty, 'nameError')
&& showErrorAndFocusIf('FieldData2', isEmpty, 'emailError')
&& showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2')
&& showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError')
&& showErrorAndFocusIf('FieldData1', isEmpty, 'questionError');
/* For debugging, lets prevent the form from submitting. */
if (formIsValid) {
alert("Valid form!");
return false;
}
return formIsValid;
}
function showErrorAndFocusIf(fieldId, predicate, errorId) {
var field = document.getElementById(fieldId);
if (predicate(field)) {
document.getElementById(errorId).style.display = 'inline';
if (field.select) {
field.select();
}
field.focus();
return false;
}
return true;
}
function isEmpty(field) {
return field.value == '';
}
function isAnInvalidEmail(field) {
var email = field.value;
var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i = 0; i < email.length; i++){
if(ok.indexOf(email.charAt(i)) < 0) {
return true;
}
}
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return re.test(email) || !re_two.test(email);
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("emailError2").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
And the cleaned up HTML:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<div>
<div class="error" id="nameError">
Required: Please enter your name
</div>
<label for="FieldData0"><strong>Name:</strong></label>
<input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
</div>
<div>
<div class="error" id="emailError">
Required: Please enter your email address
</div>
<div class="error" id="emailError2">
This doesn't look like a real email address, please check and reenter
</div>
<label for="FieldData2"><strong>Email:</strong>(will not be published)</label>
<input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
</div>
<div>
<div class="error" id="categoryError">
Please select a category from the drop-down menu
</div>
<label for="FieldData3"><strong>Category:</strong></label>
<select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select>
</div>
<div>
<div class="error" id="questionError">
Please type your question in the box below:
</div>
<label for="FieldData1"><strong>Your Question:</strong></label>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea>
</div>
<input type="submit" class="btn" value="Submit Question" name="Submit">
</form>
Regarding the error on the drop-down, don't call this line:
document.getElementById("FieldData1").select();
I seem to recall having the exact same problem a few weeks ago.
First problem: move the content of that if statement into a function...then go from there. You have about 5 pieces of code doing essentially the same thing.
Next: since you're only allowing one error message at a time, create a generic div to hold it and just move the thing. That way, you don't need to keep track of hiding certain errors, displaying others, etc.
Next: only return true or false from your check_email function...returning -1 and false, etc. is bad form even though javascript is lenient on such things.
After you have cleaned up your code, it will be much easier to debug.
I would recommend getting rid of the whole if else chain and check each on individually this this.
var error = 0;
if (value == '') {
error = 1;
// other stuff;
}
if (value2 == '') {
error = 1;
// do stuff;
}
...
if (error) {
// show error
} else {
// submit form
}
Try replacing the == for === which doesn't type cast. It might help you with the dropdown problem.
Your function is returning false and it might also return -1.
As I don't know what type cast JavaScript does with !-1 you should also do this:
check_email(...)!==false;
Instead of this:
!check_email(...)