I am trying to create what I hope is a somewhat simple donation form. There are two options to choose from:
A drop down with a text field to enter an amount
A text field to write in an other designation along with a text field to enter an amount
I've been looking through a lot of different examples of code, but I'm not entirely sure how to search the technical name for what I need. I need to have an alert appear when nothing is entered as well as an alert when only one part of 1 or one part of 2 is entered. I know this is something I need JS for, but have zero experience with it.
I found several pages that were a little helpful with validation and alert messages for multiple fields, but I think I need to have an either/or type of alert (if that makes sense). EITHER you choose from the drop down and enter an amount OR you enter something in the "Other" text field and enter an amount.
You can see my code below. I included some JS I found and tried to modify that seemed to be closest to what I'm looking for, but with my limited knowledge of the language I know it's not correct (try not to judge me). I can get an alert message that works sometimes and not for everyone. And sometimes the alert still appears when it's filled out correctly.
I feel like my brain is fried at this point, so any help you can provide is greatly appreciated. Javascript is definitely going to the top of my "Must Learn" list after this. Thank you!
<script>
function validateForm() {
var x = document.forms["form1"]["FUND1"].value;
var x = document.forms["form1"]["FUND2"].value;
var x = document.forms["form1"]["GIFT_AMOUNT1"].value;
var x = document.forms["form1"]["GIFT_AMOUNT2"].value;
if (form1.FUND1.value == '' && form1.FUND2.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
if (form1.GIFT_AMOUNT1.value == '' && form1.GIFT_AMOUNT1.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
}
</script>
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="0.00"/>
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation"/>
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="0.00"/>
</div>
<div style="clear:both; float:left;">
<p><input type="submit" value="Continue" class="continue_button" onclick="validateAndSend()"></p>
</div>
What you are doing is ok.
To improve what you are doing you can try this:
I'm paring FUND and GIFT_AMOUNT because I guess is what you are trying to do, now the alert will show when both 1s or 2s are empty.
function validateForm() {
var form1 = document.forms['form1']
if (form1.FUND1.value === '' || form1.GIFT_AMOUNT1.value === '') {
alert("please select a donation designation and an amount 1.");
return false;
}
if (form1.FUND2.value === '' || form1.GIFT_AMOUNT2.value === '') {
alert("please select a donation designation and an amount 2.");
return false;
}
return true;
}
In your form you need to initialize your GIFT_AMOUNT inputs with value="" otherwise if you compare '0.00' with '' always will be false.
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="" />
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation" />
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="" />
</div>
<div style="clear:both; float:left;">
<p>
<input type="submit" value="Continue" class="continue_button" />
</p>
</div>
</form>
There is no need to call a function in your onclick property because you are calling the submit function already to improve this behavior you can do something like this:
function submitForm() {
if (validateForm()) {
// do some stuff
}
}
and change the onsubmit property from your form
<form ... onsubmit="submitForm()">
If you are starting with javascript will be a good idea to learn how to use the console in order to debug your scripts. This article is a good point to start and as a last tip check this out.
Related
So I've been having trouble understanding why my "document.getElementbyID()" function is breaking my external script. My script and html file look like this:
function validateRegCat(obj)
{
setRegCat(obj);
var invalid = false;
if(obj.value == "Invalid")
{
alert("Please select a Registration category")
invalid = true;
}
return invalid;
}
function setRegCat(obj)
{
if(obj.value == "UWSStudent")
{
document.getElementbyId("Institution").value = "The University of Western Sydney";
document.getElementbyId("Institution").readOnly = true;
}
}
<body>
<form class="Application" action"prac1task3Form.asp" method="post" onsubmit="return finalValidate(this);" >
<div class="PersonalDetails">
<fieldset>
<legend>
<h3>Personal Details</h3>
</legend>
<!--Kept in a list to keep the form looking neat and organised-->
<ul>
<li>
<!-- Create a selection box for the user to input their Registration Category-->
<label for="RegCat"><strong>Registration Category:</strong><sup>*</sup></label>
<select name="RegCat" size="1" onblur="validateRegCat(this); setRegCat(this)" required>
<option value = "Invalid">--Choose a registration category--</option>
<option value = "UWSStudent">UWS Student</option>
<option value = "OtherStudent">Student at another Institution</option>
<option value = "UWSAcademic">UWS Academic</option>
<option value = "UWSStaff">UWS Staff</option>
<option value = "OtherAcademic">Academic from another Institution</option>
<option value = "PublicMember">Member of the public</option>
<option value = "Retired">Retired</option>
</select>
</li>
<!-- Input Institution. Sets automatically to Uws and readonly if certain registration categorys are selected-->
<li>
<label for="Institution"><strong>Institution of learning/work:</strong> </label>
<input type="text" name="Institution" id="Institution" size="30" maxlength="30"/>
</li>
</ul>
</fieldset>
</div>
</form>
</body>
I've cut the html down to only the relevant parts. What I want the script to do is to change the value of the "Institution" text input to read only and set the text displayed. However I've found that the "document.getElementbyId("Institution")" breaks the script. The script runs fine before that and when I change those lines to meaningless things such as alerts, the script functions and returns as it should.
I assume the problem is related to typos (make sure you have capital 'B' instead of 'b'): document.getElementById (https://developer.mozilla.org/it/docs/Web/API/Document/getElementById).
If you use Firebug (http://getfirebug.com/) or similar while developing you can detect these small errors easily.
I'm am fairly new to JavaScript; I have been googling all day for this but i only found how to enable and disable one textbox using one checkbox.
Here is my code
JavaScript
function enable_text(status){
status=!status;
document.sr2.other_text.disabled = status;
}
HTML
<form name=sr2 method=post>
<input type="checkbox" name=others onclick="enable_text(this.checked)">
Others
<input type=text name=other_text>
</form>
Note: the code I posted is only for a textbox that when uncheck in checkbox it will be enabled.
My question is how do you disable select tag and enable a textbox after unchecking a checkbox?
Add an id to your text box then just put the below onclick of your checkbox instead of the function call.
<form name=sr2 method=post>
<input type="checkbox" name=others onclick= "document.getElementById('id_of_txtbox').disabled=this.checked;">Others
<input type=text name=other_text>
Here's the HTML
<input type="text" id="txt" disabled="disabled"/>
<select name="sel" id="sel">
<option value="test1">Test 1</option>
</select>
<input type="checkbox" name="vehicle" value="Car" checked="checked" onclick="enableText(this.checked)">Uncheck to Disable Select and Enable Text
And the JavaScript is
function enableText(checked){
if(!checked){
document.getElementById('sel').disabled = true;
document.getElementById('txt').disabled = false;
}
else{
document.getElementById('sel').disabled = false;
document.getElementById('txt').disabled = true;
}
}
Select is disabled and text is enabled on uncheking the checkbox and vice versa. Hopefully that helps.
Based on your question, are you trying to present a dropdown but then allow them to enter other values not in the dropdown?
If so, here is another way to approach it:
HTML:
<select name="RenewalTerm" id="RenewalTerm">
<option value="12">12 Month</option>
<option value="24">24 Month</option>
<option value="36">36 Month</option>
<option value="Other">Other</option>
</select>
<span id="RenewalTermOtherFields">
<label labelfor="RenewalTermManual" >Enter Renewal Term: </label>
<input type="text" name="RenewalTermManual" id="RenewalTermManual" />
</span>
JavaScript/jQuery:
$(document).ready(function() {
$('#RenewalTermOtherFields').hide();
$('#RenewalTermManual').val($('#RenewalTerm').val());
$('#RenewalTerm').change(function() {
var selectedItem = $("select option:selected").val();
if (selectedItem !== 'Other') {
$('#RenewalTermOtherFields').hide();
$('#RenewalTermManual').val($('#RenewalTerm').val());
}
else
{
$('#RenewalTermManual').val('');
$('#RenewalTermOtherFields').show();
}
});
});
See It In Action!: http://eat-sleep-code.com/#/javascript/dropdown-with-other-field
This will allow you to select "other" from the list, and when you do it will automatically display a textbox for free-form entry.
I doing a form for a small project, and having a trouble trying to validate the select option
hope someone can help
THanks in advance
HTML:
<form method="post" name="vehicleform" action=" " onSubmit="return (validateForm())">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
Phone Number <font size="1px">(ex. 123-456-7890)</font>: <input type="text" name="phonenumber"><br>
Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select><br>
JS:
function validateForm(){
var d = document.forms['vehicleform']['location'].value;
if( document.vehicleform.location.value == "-1" )
{
alert("Please select your location");
return false;
}
}
There is no need for grouping in the listener, and passing this gives immediate access to the form:
<form ... onsubmit="return validateForm(this)">
You only need to check the selected index to see if something other than the first option (or no option all) is selected:
function validateForm(form) {
if (form.location.selectedIndex < 1) {
alert("Please select your location");
return false;
}
}
And as suggested in the comments, make the first option selected by default:
<select name="location">
<option value="-1" selected>Select one..
<option value="lota">Lot A
as browsers may not make any option selected by default and users won't see "Select one...". That should be a label anyway to assist with accessiblity.
http://jsfiddle.net/LVBSZ/1/
You have no submit button in your code and close tag for form. The other works for me
<script>
function validateForm() {
if (document.forms['vehicleform'].location.value == "-1") {
alert("Please select your location");
return false;
}
}
</script>
<form method="post" name="vehicleform" onSubmit="return validateForm()">
First Name:
<input type="text" name="fname">
<br>Last Name:
<input type="text" name="lname">
<br>Phone Number <font size="1px">(ex. 123-456-7890)</font>:
<input type="text" name="phonenumber">
<br>Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select>
<br>
<input type="submit" value="Submit">
</form>
I'm trying to redirect to a page based on the selected option, but with javascript validation.
I have this form:
<form action="verify.php" method="post">
<label for="class_year" class="inner_text">Year Range</label>
<select id="class_year" name="year">
<option value="a">50</option>
<option value="b">60</option>
<option value="c">70</option>
<option value="c">80</option>
<option value="c">90</option>
</select>
<label for="dob" class="inner_text">Date of Birth (YY-MM-DD)</label>
<input name="dob" type="text" class="false" id="dob" maxlength="10">
</form>
Now I have this verify.php file that redirect for example to a.html if you choose 1950:
<?php
header('Location: '.$_POST['year'].'.php');
?>
What I want to do is to verify what my visitors choose. For example if you write 51-02-28 in text box, that mean you must choose 1950, so you will be redirected to a.html; if you write for example 61-02-28 but you choosed 1950 then you can't submit the form an a alert will show. And if you write anything else for example 41-02-29, then you will be alerted too and the form will not be submited. The first 2 option redirect to a.html and b.html, the last 3 options redirect to the same page c.html .
In conclusion I need to validate only the first number from the text box. I don't know how to do that with javascript!
I apreciate any and all comments, thank you.
You can go ahead with validation by using normal javascript and while redirecting you can use something like this instead of PHP redirect
Your code should be something like this:
<form action="verify.php" method="post" id="mainForm">
<label for="class_year" class="inner_text">Year Range</label>
<select id="class_year" name="year">
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
</select>
<label for="dob" class="inner_text">Date of Birth (YY-MM-DD)</label>
<input name="dob" type="text" class="false" id="dob" maxlength="10">
</form>
<script type="text/javascript">
$("#mainForm").submit(function(){
var yearVal = $("#dob").val().split("-")[0];
var redirectObj= [
['50','a'],
['60','b'],
['70','c'],
['80','c'],
['90','c']
];
if(parseInt(yearVal)>parseInt($("#class_year").val()) && parseInt(yearVal)<(parseInt($("#class_year").val())+10))
{
var redirectPage = "";
redirectObj.forEach(function(entry) {
if(parseInt(entry[0])==(Math.round(parseInt(yearVal)/10))*10)
{
redirectPage = entry[1];
}
});
window.location = redirectPage+".php";
}
else
{
alert("you have entered invalid value");
return false;
}
});
In case you want to redirect it to the first letter of the textbox you can use something like this
window.location = $("#dob").val().charAt(0)+".php";
You may check the working code at http://jsfiddle.net/amanchhabra1990/Uy78a/
Please let me know if this helps you.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to make a javascript to be shown if somebody chooses option A to show the javascripts for the A1 , A2 , A3 and if they choose B to show javascripts for the B1 , B2 , B3. So the A and B it will firstly asked as options from a select tag
For example:
<select name="AorB" >
<option value="" selected="selected">Select...</option>
<option value="A" >Option A</option>
<option value="B" >Option B</option>
</select>
I'm using this way of javascript (Error Alerts):
<SCRIPT language=JavaScript>
<!--
function check(form) {
if (form.Password.value == "")
{ alert("Please enter your Password."); form.Password.focus(); return;}
if (form.Password.value.length < 8)
{ alert("Please enter a valid Password."); form.Password.focus(); return;}
form.submit()
}
//-->
</SCRIPT>
P.S: I don't want to make complications when they choose A to get B option javascripts or reverse.
added - explain: i mean if We select OPTION A there will be shown some Input-s ....and javascript will ask only for the shown input-s so it means OPTION A input-s ... but not to ask for OPTION B input-s too even that they're not shown cause we didnt select OPTION B ... i hope i explained a little for you.
What I understand of your question is that you want a select box and this will determine what fields show up on the form. Then you want the validation script to only validate those fields that show up. This would best be handled with JQuery. Here is some working code to give an example, and a fiddle.
HTML
<div id="wrapper">
<form id="myForm" name="myForm" method="POST" action="http://www.google.com">
<select id="option" name="option">
<option value="X">Choose One...</option>
<option value="A">Option A</option>
<option value="B">Option B</option>
</select>
<div id="optionset-a">
<p>
Input A1: <input name="a1" id="a1" class="option-a" type="textfield" /><br />
Input A2: <input name="a2" id="a2" class="option-a" type="textfield" /><br />
Input A3: <input name="a3" id="a3" class="option-a" type="textfield" /><br />
</p>
</div>
<div id="optionset-b">
<p>
Input B1: <input name="b1" id="b1" class="option-b" type="textfield" /><br />
Input B2: <input name="b2" id="b2" class="option-b" type="textfield" /><br />
Input B3: <input name="b3" id="b3" class="option-b" type="textfield" /><br />
</p>
</div>
<input type="submit" id="submit-button" name="submit" value="Submit" />
</form>
</div>
JQuery
$('#optionset-a').hide();
$('#optionset-b').hide();
$('#submit-button').hide();
$('#option').change(function() {
if ($('#option').val() == 'A') {
$('#optionset-b').hide();
$('#optionset-a').show();
$('#submit-button').show();
} else if ($('#option').val() == 'B') {
$('#optionset-a').hide();
$('#optionset-b').show();
$('#submit-button').show();
}
});
$('#submit-button').click(function() {
var validation = true;
if ($('#option').val() == 'A') {
$('.option-a').each(function() {
if ($(this).val() == '') {
$(this).css('border','1px solid red');
validation = false;
}
});
}
if ($('#option').val() == 'B') {
$('.option-b').each(function() {
if ($(this).val() == '') {
$(this).css('border','1px solid red');
validation = false;
}
});
}
if (validation) {
document.forms["myForm"].submit();
} else { alert('Please fill in all fields.'); }
});
You can easily check the current value of a select tag with:
alert(document.getElementById('AorB').value);
This will alert the current value of the select tag.
You can then check the value whenever the value changes with the onChange event:
<select id="AorB" onchange="alert(document.getElementById('AorB').value);">
<option value="" selected="selected">Select...</option>
<option value="A" >Option A</option>
<option value="B" >Option B</option>
</select>
Here is a jsFiffle example you can use.
You can then do some JavaScript dependent on what the value is, I will not write you the whole code though.
I hope this helps!