Radio Button not Working in ie - javascript

I have 4 radio button in my form, once i submit the form any of the radio button should checked, if not a alert message will be displayed. its working properly in chrome, firefox, but in ie one i checked the radion it always showing the alert so i cant submit the form, i have given my code below please help me
PHP:
<form action="user_register.php" method="POST" name="myForm" onsubmit="return validateForm()" enctype="multipart/form-data">
<label>USERNAME:</label></td>
<input type="text" name="username" class="regtext" required/>
<label>RESIDING CITY:</label></td>
<input type="text" name="city" class="regtext" required/>
<label>I'M A</label>
<label>ARTIST &nbsp <input type="radio" value="1" name="user_type" > </label>&nbsp
<label>MODEL &nbsp <input type="radio" value="2" name="user_type"></label>&nbsp
<label>COMPOSER &nbsp <input type="radio" value="3" name="user_type" ></label>&nbsp<br>
<label>BEAT MAKER &nbsp <input type="radio" value="4" name="user_type" ></label>&nbsp
<label>NONE &nbsp <input type="radio" value="0" name="user_type" ></label>
<label> <input type="checkbox" value="1" name="letter" > &nbsp I WOULD LIKE TO RECEIVE YOUR NEWSLETTER</label>
</div>
<div class="mainhead">
<input type="submit" name="register" class="submit" value="SEND AND REGISTER NOW">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>

Problem is that for IE, document.forms["myForm"]["user_type"] is an HTMLCollection and has no value
Solution is to change
var user_type = document.forms["myForm"]["user_type"].value;
to
var user_type = document.querySelector('form[name="myForm"] input[name="user_type"]:checked').value;

What i observed is :
No name province present in code (what you gave). If you include it here, it will not work.
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
After removing province validation. It started working.
<script type="text/javascript">
function validateForm() {
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
So, as Mr Rayon Dabre said "There is no element having name as province". So, i also agree with him. Remove province validation from validateForm() function (as it is not used in <from></form>)

This code should do the trick:
function validateForm() {
var user_type = document.getElementsByName('user_type');
var u_type = '';
for (var i = 0, length = user_type.length; i < length; i++) {
if (user_type[i].checked) {
// do whatever you want with the checked radio
u_type = user_type[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
if (u_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.getElementsByName('letter')[0].checked;
if (letter == "" || letter == undefined) {
alert("Select that you want to receive news letter");
return false;
}
}

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...

Cannot set the value properly in javascript

I've 6 following radio buttons
<input type="text" id="status" name="status">
<input type="radio" name="orderReceivingKeysPresent" id="orderReceivingKeysPresent_Y" value="1" onclick="checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingKeysPresent" id="orderReceivingKeysPresent_N" value="0" onclick="checkKeyAndTitle(this);"> No
<input type="radio" name="orderReceivingTitlePresent" id="orderReceivingTitlePresent_Y" value="1" onclick="checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingTitlePresent" id="orderReceivingTitlePresent_N" value="0" onclick="checkKeyAndTitle(this);"> No
<input type="radio" name="orderReceivingReturnToOwner" id="orderReceivingReturnToOwner_Y" value="1" onclick="hideAndShowReturnToOwner(this); checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingReturnToOwner" id="orderReceivingReturnToOwner_N" value="0" onclick="hideAndShowReturnToOwner(this); checkKeyAndTitle(this);" checked="checked"> No
No I'm using javascript for assiging values. I've created javascript function but it isn't working properly and I can't figure it out. How to do it?
function checkKeyAndTitle(getObj) {
if(getObj.name == "orderReceivingKeysPresent") {
if(getObj.value == "1") {
$("#status").val('Delivered');
} else {
$("#status").val('Missing Keys');
}
}
else {
if(getObj.value == "1") {
$("#status").val('Delivered');
} else {
$("#status").val('Missing Title');
}
}
}
Now orderReceivingReturnToOwner is checked to no by default.
When I click at orderReceivingKeysPresent to yes and orderReceivingTitlePresent to no then status should be Missing Title and when orderReceivingKeysPresent no and orderReceivingTitlePresent yes status should be Missing Keys and when both are yes status should be Delivered and also check this one to when orderReceivingReturnToOwner yes status should be Return To Owner. Help suggest me how to do it.
$("input[type='radio']").on("click", function () {
var keyRadioVal = $('input:radio[name=orderReceivingKeysPresent]:checked').val();
var titleRadioVal = $('input:radio[name=orderReceivingTitlePresent]:checked').val();
var ownerRadioVal = $('input:radio[name=orderReceivingReturnToOwner]:checked').val();
if (ownerRadioVal == 1) {
$("#status").val('Return To Owner');
} else if (keyRadioVal == 1 && titleRadioVal == 0 && ownerRadioVal == 0) {
$("#status").val('Missing Title');
} else if (titleRadioVal == 1 && keyRadioVal == 0 && ownerRadioVal == 0) {
$("#status").val('Missing Keys');
} else if (titleRadioVal == 1 && keyRadioVal == 1 && ownerRadioVal == 0) {
$("#status").val('Delivered ');
} else {
$("#status").val('Missing Keys');
}
});
what i had done is getting value of each radio button which is selected on selection change of every single radio button and check all 3 case.
rest in all case Missing key will be shown that you can accordingly.

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 do I disable form dropdown option using 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.

Categories