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; }
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 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 ==>
I am just wondering why the label's text which i am setting below doesn't persists. If the user enters valid username & password say(xxx & yyy) then the label should set with Welcome xxx, else set with "Login Failed". Here i see the label is set with right text, but in a fraction of second the page refreshes and all fields are set empty and the label text is erased. How to overcome this? I am trying in Firefox.
Following is my html code:
<html>
<body>
<form>
User Name: <input type="text" id="uname"/><br/><br/>
Password : <input type="text" id="pwd"/><br/><br/>
<input type="submit" value="Login"onclick="validateLogin()"/><br/>
<label id="label1" /><br/>
<label id="label2" /><br/>
</form>
<script>
function validateLogin()
{
var v1=document.getElementById("uname").value;
var v2=document.getElementById("pwd").value;
if(v1=="xxx" && v2=="yyy")
{
document.getElementById("label1").innerHTML="Welcome :"+v1;
}
else
{
alert("Invalid login");
document.getElementById("label2").innerHTML="Login Failed!!!";
}
}
</script>
</body>
</html>
Change markup like this
<input type="submit" value="Login"onclick="return validateLogin()"/> <!-- added return -->
Javascript
if (v1 == "xxx" && v2 == "yyy") {
document.getElementById("label1").innerHTML = "Welcome :" + v1;
return false; /* return */
} else {
alert("Invalid login");
document.getElementById("label2").innerHTML = "Login Failed!!!";
return false; /* return */
}
Demo
Note: This will work as expected but those values need to post on server side while condition is true so in if block write your code to post data on server rather than printing it to the label and don't forget to remove return false from if after writing the code
I have member status select box in that i have open,read,close option is there.So when i'm selecting open or read and click update button it will updateing something.and i'm selecting close it display dialog box(Are you sure want close this)if yes it goes to some page or goes to no page.(I want to dispaly confirm box only particular value(22 only).
Anybody help on this one(js or jquery).It is smarty application
Here is my code
<html>
<head>
<script type="text/javascript">
function showClose() {
var val = document.getElementById('sel_state').value;
if (val == '22') {
var state = confirm("Are you sure want to change member status??");
if (state == true) {
alert('yes');
} else {
alert('no');
}
} else {
alert('no');
}
}
</script>
</head>
<body>
<form method="post" action="/admin/member-modify-{$member->id}">
<label>Member state</label>
<select name="sel_state" class="validate" id="sel_state">
<option value=1>open</option>
<option value=2>read</option>
<option value=22>close</option>
</select>
<input name="submit" value="Validate" id="member_state_submit" type="submit" class="submit" Onclick="showClose();" />
</form>
</body>
</html>
All what you have to do is to wrap your JS code within {literal}{/literal} tags like this :
{literal}
<script type="text/javascript">
function showClose() {
var val = document.getElementById('sel_state').value;
if (val=='22') {
var state = confirm ("Are you sure want to change member status??");
if (state == true) {
alert('yes');
} else {
alert('no');
}
} else {
alert('no');
}
}
</script>
{/literal}
In Smarty, anything within {literal}{/literal} tags is not interpreted, but displayed as-is. This will avoid interfering with the template delimiter syntax. Check the documentation.
This is simple with jquery
var value = $('#selector').text()
if (value == 22){
//do something here
}
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(...)