How do I disable form dropdown option using javascript - javascript

I'm trying to disable the "name" text field in the form when "Choose" is selected in the drop down after the page loads (it's disabled when the page loads) ie after I've chosen one of the other two options that disable or enable that field, when I return to "Choose" i'd like the same field to disable. I can't see why the javascript I've written would prevent this from happening. Thanks!
<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value === defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value === "") {
thisfield.value = defaulttext;
}
}
function checkPickup() {
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
/* Reset form values */
form.name.value = "His/her name";
}
}
</script>
<script type="text/javascript">
function validate(form) {
var errmsg = "Oops, you're required to complete the following fields! \n";
// Various other form validations here
// Validate "Pickup"
if (form.os0.value === "") {
errmsg = errmsg + " - Choose pickup or delivery\n";
}
// Validate "phone"
if (form.phone.value === "" || form.phone.value === "Mobile's best!") {
errmsg = errmsg + " - Your phone number\n";
}
if (form.os0.value != "Pickup from Toowong, Brisbane") {
// Validate "name"
if (form.name.value === "" || form.name.value === "His/her name") {
errmsg = errmsg + " - His/her name\n";
}
}
// Alert if fields are empty and cancel form submit
if (errmsg === "Oops, you're required to complete the following fields! \n") {
form.submit();
} else {
alert(errmsg);
return false;
}
}
</script>
</head>
<body>
<form name="form" action="https://www.paypal.com/cgi-bin/webscr" method="post" onSubmit="return validate(form)">
<p class="row">
<input type="hidden" name="on0" value="Pickup and delivery" />Pickup and delivery<br />
<select name="os0" onchange="checkPickup()">
<option value="" selected >Choose</option>
<option value="Pickup from Toowong, Brisbane">Pickup from Toowong, Brisbane $1.00 AUD</option>
<option value="Brisbane +$23.60">Brisbane +$23.60 =$1.00 AUD</option>
</select>
</p>
<p class="row">Your daytime phone number<br />
<input type="text" name="phone" value="Mobile's best!" onclick="clickclear(this, 'Mobile\'s best!')" onblur="clickrecall(this,'Mobile\'s best!')" />
</p>
<p class="row">Recipient's name<br />
<input style="color: #ccc" class="name" type="text" name="name" value="His/her name" onclick="clickclear(this, 'His/her name')" onblur="clickrecall(this,'His/her name')" disabled />
</p>
<input name="custom" type="hidden" />
<input type="hidden" name="currency_code" value="AUD" />
<input class="button" type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online." />
<img alt="" border="0" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1"> -->
</form>
</body>
</html>

This may be a simple misunderstanding of what you've written:
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
translates to the following in plain english:
If the value is NOT "Pickup from Toowong, Brisbane", enable the field, otherwise disable it.
which is equivalent to:
ONLY disable the field when the value is "Pickup from Toowong, Brisbane".
I believe the logic you're looking for is:
if (form.os0.value == "Brisbane +$23.60" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
though it might be prettier to code this with a switch statement due to the involvement of specific cases.
See DEMO

did you intend to type double equal to (==) or is the triple equal to (===) a typo in the question? Based on looking at your code, it looks to me like you need a double equal to (==) not a triple. I think triple may mean something else.

Related

JavaScript input type validation

I can't seem to figure out the proper JavaScript to validate this form. Please help/provide feedback!
Essentially, my script should validate whether the user has entered data in the input text box, has checked a radio button, has checked at least one checkbox, and has selected an option from the select items.
Also the form uses a submit button to invoke the validation script, so that the form is processed only when the form fields are validated and accepted. If a field is invalid then display a message to the user.
Also need to make sure the form doesn't automatically reset every time the user gets a validation error.
<body>
<section>
<h1 style="text-align: center">Vacation Interest Vote Form</h1>
<form name="VacayForm" action="mailto:" onsubmit="return Validate1()" method="post">
<p>Name:<input type="text" name="name" size="25"></p><br>
<p>Do You Prefer an international destination?</p>
<p>Domestic<input type="radio" name="domint" value="domestic"></p>
<p>International<input type="radio" name="domint" value="international"></
<br>
<p>Where would you like to go?</p>
<select type="text" name="continent" value="select" size="1">
<option value="domestic">Domestic</option>
<option value="europe">Europe</option>
<option value="camerica">Central America</option>
<option value="asia">Asia</option>
<option value="aus">Australia</option>
</select>
<br>
<p>Check the box to act as your digital signature to cast your vote
<input type="checkbox" value="agree" name="sig">
<input type="submit" value="Send" name="submit" onclick="if(!this.form.sig.checked){alert('You must agree to cast your vote by checking the box.');
return false}">
<input type="reset" value="Reset"name="reset">
</form>
</section>
<script>
function Validate1() {
var nam = document.forms["VacayForm"]["name"];
var dom = document.forms["VacayForm"]["domestic"];
var int = document.forms["VacayForm"]["international"];
var sel = document.forms["VacayForm"]["select"];
var agree = document.forms["VacayForm"]["agree"];
//if (name.value == "")
//{
// window.alert("Please enter your name.");
// name.focus();
// return false;
//}
if( document.VacayForm.name.value == "" )
{
alert( "Please provide your name!" );
document.VacayForm.name.focus() ;
return false;
}
if (domestic.value == "")
else (international.value == "")
{
window.alert("Please select domestic or international preference to proceed.");
domestic.focus();
international.focus();
return false;
}
if (select.selectedIndex < 1)
{
alert("Please select where you prefer to visit");
select.focus();
return false;
}
return true;
}
//function Validate2() {
// var radios = document.getElementsByName("yesno");
// var formValid = false;
// var i = 0;
// while (!formValid && i < radios.length) {
// if (radios[i].checked) formValid = true;
// i++;
// }
// if (!formValid) alert("Must check an option!");
// return formValid;
//}
</script>
</body>
</html>
Your validate function could look like this...
function validate() {
var form = document.forms.VacayForm;
var name = form.name;
var domInt = form.domint;
var continent = form.continent;
var agree = form.agree;
if (!name.value) {
alert( "Please provide your name!" );
name.focus();
return false;
}
if (!domInt.value) {
alert( "Please select domestic or international preference to proceed" );
domInt.focus();
return false;
}
if (!continent.value) {
alert("Please select where you prefer to visit");
continent.focus();
return false;
}
if (!agree.checked) {
alert("Please check agree to continue");
agree.focus();
return false;
}
return true;
}
This article from Javascript.info website teaches how to use forms and form elements...

Checking if integer JavaScript forms

I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}

onSubmit Function not able to call a function inside of it

I am trying to make a form. I want it to check the radio buttons to see if they have been clicked, and if not to have a message to the user to check one.
I tried to just enter it, then I tried to continue my else if statements with it (got error messages), then I tried making a function within the onsubmit function (it simply didn't initiate), then I tried making a function outside of the onsubmit function and am trying to call it, but it does not initiate. I've even tried moving the functions on top or below the onsubmit function.
I made the submitYesCancel to see if the problem was with the radioB function, but neither function will initiate.
I'm hopelessly stuck. Please help.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
/* <![CDATA[ */
function confirmPassword()
{
if (document.forms[0].password_confirm.value != document.forms[0].password.value)
{
window.alert("You did not enter the same password!");
document.forms[0].password.focus();
}
}
function submitForm()
{
submitYesCancel();
if (document.forms[0].name.value == ""
|| document.forms[0].name.value == "Your Name")
{
window.alert("You must enter your name.");
return false;
}
else if (document.forms[0].emailAddress.value == ""
|| document.forms[0].emailAddress.value == "Your Email")
{
window.alert("You must enter your email address.");
return false;
}
else if (document.forms[0].password.value == ""
|| document.forms[0].password_confirm.value == "")
{
window.alert("You must enter a password.");
return false;
}
else if (document.forms[0].sq.value ==""
|| document.forms[0].sq.value == "Your Security Answer")
{
window.alert("You must enter a security answer.");
return false;
}
radioB();
return true;
}
function submitYesCancel()
{
var submitForm = window.confirm("Are you sure you want to submit the form?");
if (submitForm == true)
{
return true;
return false;
}
}
function radioB()
{
var radioButton = false;
for (var i = 0; i < 4; ++i)
{
if (document.forms[0].special_offers[i].checked == true)
{
radioButton = true;
break;
}
}
if (radioButton != true)
{
window.alert("You must select a radio button.");
return false;
}
}
function confirmReset()
{
var resetForm = window.confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<form>
<h2>Personal Information</h2>
<p>Name:<br />
<input type = "text" name = "name" placeholder = "Your Name" size = "50"/></p>
<p>Email Address:<br />
<input type = "text" name = "emailAddress" placeholder = "Your Email" size= "50" /></p>
<h2>Security Information</h2>
<p>Please enter a password of 8 characters or less: <br />
<input type = "password" name = "password" maxlength = "8" /></p>
<p>Confirm password<br />
<input type = "password" name = "password_confirm" size = "50" onblur = "confirmPassword();" /></p>
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question">
<option value = "mother">What is your Mother's maiden name?</option>
<option value = "pet">What is the name of your pet?</option>
<option value = "color">What is your favorite color?</option>
</select></p>
<p><input type = "text" name = "sq" placeholder = "Your Security Answer" size = "50" /></p>
<h2>Preferences</h2>
<p>Would you like special offers sent to your email address?<br />
<input type = "radio" name = "radioButton" value = "Yes" />Yes<br />
<input type = "radio" name = "radioButton" value = "No" />No<br /></p>
<p>Are you interested in special offers from: <br />
<input type = "checkbox" name = "sCheckboxes" value = "e" />Entertainment<br />
<input type = "checkbox" name = "sCheckboxes" value = "b" />Business<br />
<input type = "checkbox" name = "sCheckboxes" value = "s" />Shopping<br /></p>
<button onclick="return submitForm();">Submit</button>
<button onclick="return confirmReset();">Reset</button>
</form>
</body>
</html>
The reason that it does not work because your Javascript is completely wrong.
}
radioB();
else // <--- what does it mean?
return true;
And
else if (radioButton ! = true) {
// <-- you have else if, but there is no if block and it is != not ! =
Next time when your Javascript does not work, try to see the error first. You can easily do this in Google Chrome. Hit Ctrl + Shift + J, go to Console tab. Then, fix each error when you encounter it until there is no more error.

Javascript Validation for all field with Required attribute

I've searched high and low for the answer to this but can't find it anywhere.
I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.
In case that input[type=submit] is used, you don't need any JavaScript
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="submit" name="submit" value="Submit" />
</form>
Working jsBin
But if input[type=button] is used for submitting the form, use the snippet below
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="button" name="button" value="Submit" />
</form>
window.onload = function () {
var form = document.getElementById('theForm');
form.button.onclick = function (){
for(var i=0; i < form.elements.length; i++){
if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
alert('There are some required fields!');
return false;
}
}
form.submit();
};
};
Wotking jsBin
Many years later, here is a solution that uses some more modern Javascript:
for (const el of document.getElementById('form').querySelectorAll("[required]")) {
if (!el.reportValidity()) {
return;
}
}
See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)
You can use Constraint validation API, which is supported by most browsers.
I'm late to the party but this worked for me.
<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
//success code here
return true;
}
Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.
this will be validating all your form field types
$('#submitbutton').click(function (e) {
e.preventDefault();
var form = document.getElementById("myForm");
var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
var selects = form.getElementsByTagName("select");
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "hidden") {
continue;
}
if(input.type == "radio" && !input.checked) {
not_pass = true;
}
if(input.type == "radio" && input.checked){
not_pass = false;
break;
}
if(input.type == "text" && !input.value) {
not_pass = true;
}
if(input.type == "text" && input.value){
not_pass = false;
break;
}
if(input.type == "number" && !input.value) {
not_pass = true;
}
if(input.type == "number" && input.value){
not_pass = false;
break;
}
if(input.type == "email" && !input.value) {
not_pass = true;
}
if(input.type == "email" && input.value){
not_pass = false;
break;
}
if(input.type == "checkbox" && !input.checked) {
not_pass = true;
}
if(input.type == "checkbox" && input.checked) {
not_pass = false;
break;
}
}
for(var i = 0, len = selects.length; i < len; i++) {
select = selects[i];
if(!select.value) {
not_pass = true;
break;
}
}
if (not_pass) {
$("#req-message").show();//this div # in your form
return false;
} else {
//do something here
}
});
If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.
<select id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
$("select[name='country_code']").change(function() {
if ($(this).val() == "US") {
$("select[name='state_code'] option").removeClass('hidden');
$("select[name='state_code'] option").addClass('required');
} else {
} else {
$("select[name='state_code'] option").addClass('hidden');
}
});
</script>
<label for="state_code">State/Province</label>
<select id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.

How to check if the user has not entered the data to a form (befor sending)?

I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you

Categories