Radio button validaton - javascript

I am trying to get a couple of radio buttons to validate using JavaScript/HTML, but I am having problems. The piece of script I am having trouble with is as follows -
if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false ))
{
alert( "Please select your sex" );
return false;
}
Basically I want it to return an alert if neither radio button options are selected. At the moment when submitted the form is refreshing itself and not providing any alerts. Any advice would be appreciated!
The relevant HTML I have been provided to work with is -
<form id="RegistrationForm" onsubmit="ValidateForm()" action="">
<fieldset>
<legend>Registration Form</legend>
<label for="username">User Name: </label>
<input type="text" class="input" id="username"/><br />
<label for="password">Password: </label>
<input type="password" class="input" id="password"/><br />
<label for="repassword">Re-Type Password: </label>
<input type="password" class="input" id="repassword"/><br />
<label for="email">Email Address: </label>
<input type="text" class="input" size="30" id="email"/><br />
<label>Age: </label>
<select id ="age" name="age">
<option value=""> --- </option>
<option value="0-18">0-18</option>
<option value="18-30">18-30</option>
<option value="30-50">30-50</option>
<option value="50+">50+</option>
</select><br/>
<label for="sexm">Sex:</label>
<input type="radio" id="sexm" name="sex" value="male" />Male<br/>
<label for="sexf"> </label>
<input type="radio" id="sexf" name="sex" value="female" />Female<br/>
<input type="checkbox" name="agree" id="agree" value="agree"/>
<label for="agree">I accept the terms and cond.</label> <br/>
<label> </label>
<input type="submit" value="Submit" class="button" />
</fieldset>
</form>

Try this code in your javascript <script> tag
function ValidateForm () {
if ( ( document.getElementById("sexm").checked == false ) && ( document.getElementById("sexm").checked == false ))
{
alert( "Please select your sex" );
return false;
} else {
return true;
}
}
Replace it with your code
if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false ))
{
alert( "Please select your sex" );
return false;
}

Use a for loop to check whether your user has selected any value or not, if not, than throw an alert and use return false to prevent your form being submitted.
Demo
var ischecked = null;
var radios = document.getElementsByName('sex');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
ischecked = radios[i];
}
}
if(ischecked==null) {
alert('Please choose your Sex');
return false;
}
Save the above code in the function, and call it on submit of your form.
Demo 2 (Validate on submit)
Note: You need to use onsubmit="return ValidateForm();"

try this ...
<script type="text/javascript">
function validate()
{
var o = document.getElementById('sexm');
var t = document.getElementById('sexf');
if ( (o.checked == false ) && (t.checked == false ) )
{
alert ("please select your sex" );
return false;
}
return true;
}
</script>

Related

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

How not to open a window if the form fields are not filled?

I have this submit button on my form with a jQuery action to open a window depending on the users choice. However, I just want the window to open if the fields are filled. I have this code and I want to merge it with an if.
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function() {
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
For exemple:
IF (#FORM).REQUIRED = TRUE {
(#BUTTON).WINDOWOPEN
}
Thanks
Because you using a submit button you will need to return false, in case if you don't want to do anything. Before that, you need also to check if your required field are empty or not. (i.e. $(your field).val() === "" then it's empty, if all you need have, then call the window.open() function.
Note: you can merge multiple fields for checking ie: $(".your_field1, .your_field2, .your_field3").val() === "" however this is an OR operation.
One possible solution:
$(function() {
$('#btnget').click(function() {
let isEmpty = false;
$('#data_form input,textarea,select').filter(':visible').each(function(i) {
if ($(this).val() === "") {
isEmpty = true;
return false;
}
});
if (isEmpty) {
return false;
}
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="data_form" action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
If you want only for the required fields, than use filter('[required]:visible') instead of filter(':visible').

Validation on other when more than one checkbox is checked

I have a form that has series of checkboxes. When the other checkbox is selected an alert appears if you don't fill in the other textbox.
If I select more than one checkbox it doesn't validate at all?
<form>
<div id="form-2" class="pages active" data-page="form-2" style="display: block;">
<p>Please indicate below the quality issue(s) you were not happy with. Pick as many options as apply. <span class="required">*</span></p>
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="test">
<input type="checkbox" name="qual-form-2[]" value="Other, please specify in the box below">
<input type="text" name="qual-form-other-form-2" value="" size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false">
<button class="next-page" data-page-id="form-2">Next</button>
</div>
</form>
<script>
if (pageCurrent.data('page') == 'form-2') {
var answer = pageCurrent.find('input[name="qual-form-2[]"]:checked').val();
if ( (answer == 'Other, please specify in the box below') && ($('input[name="qual-form-other-form-2"]').val().length > 0)) {
$('input[name="qual-form-other-form-2"]').removeClass('empty');
return true;
} else if ( (answer == 'Other, please specify in the box below') && (!$('input[name="qual-form-other-form-2"]').val().length > 0)) {
alert('Please specify other');
$('input[name="qual-form-other-form-2"]').addClass('empty');
return false;
} else if ( (answer == 'Other, please specify in the box below') && (!$('input[name="qual-form-other-form-2"]').val().length > 0) && ($('input[name="qual-form-2[]').is(":checked"))) {
alert('Please specify other');
$('input[name="qual-form-other-form-2"]').addClass('empty');
return false;
} else if ($('input[name="qual-form-2[]').is(":checked")) {
return true;
} else {
alert('Validation errors occurred. Please confirm the fields and submit it again.');
}
}
</script>
Try this : change your button type="button" and call below script.
$(function(){
$('.next-page').click(function(){
var checkCount = $('input[name="qual-form-2[]"]:checked').length;
//check atleast one checkbox checked
if(checkCount > 0)
{
var checkOther = $('input[name="qual-form-2[]"]:last');
var checkNotOther = $('input[name="qual-form-2[]"]:checked').not(checkOther);
//if 'other' and any of the rest is checked show alert
if(checkNotOther.length > 0 && checkOther.is(':checked'))
{
$('input[name="qual-form-other-form-2"]').addClass('empty');
alert('Please select either "Other" or another checkbox');
}
//if other checked and input is empty show alert
else if(checkOther.is(':checked') && $('input[name="qual-form-other-form-2"]').val() == "")
{
$('input[name="qual-form-other-form-2"]').addClass('empty');
alert('Please specify other');
}
else
{
alert('Validation Succeeded');
}
}
else
{
alert('Please check atleast one checkbox');
}
});
});
JSFiddle Demo

Form submitted though Ajax is submitting multiple times

When I submit this form though Ajax, Ajax posts it multiple times, sometimes posting it up to 10 times, even though the submit button is only clicked once. I don't understand why it is doing this. Any help would be great!
Here is my code:
<script type="text/javascript">
var messageDelay = 2000;
$( init );
function init() {
$('#messageform').show().submit( submitForm );
$('#rtypeshow').hide();
$('a[href="#messageform"]').click( function() {
$('#content').fadeTo( 'slow', .2 );
$('#messageform').fadeIn( 'slow', function() {
$('#senderName').focus();
} )
return false;
} );
$(document).ready(function (){
$("#messagetable").load("messagetable.php");
$("#etype").change(function() {
if ($(this).val() != "0") {
$("#rtypeshow").show();
$('#datepicker').attr('required', 'required');
}else{
$("#rtypeshow").hide()
$("#allowed").hide;
$('#datepicker').removeAttr('required');
$('#allowed1').removeAttr('required');
}
});
});
$(document).ready(function (){
$("#rtype").change(function() {
var selection = $(this).val();
if (selection == "1") {
$("#allowed").show();
$('#allowed1').attr('required', 'required');
}else{
$("#allowed").hide();
$('#allowed1').removeAttr('required');
}
});
});
}
function submitForm() {
var messageform = $(this);
if ( !$('#ename').val() || !$('#message').val() ) {
$('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
messageform.fadeOut().delay(messageDelay).fadeIn();
} else {
$('#sendingMessage').fadeIn();
messageform.fadeOut();
$.ajax( {
url: messageform.attr( 'action' ) + "?ajax=true",
type: messageform.attr( 'method' ),
data: messageform.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();
if ( response == "success" ) {
$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#ename').val( "" );
$('#message').val( "" );
$('#datepicker').val( "" );
$('#allowed1').val( "" );
$('#allowed2').val( "" );
$('#allowed3').val( "" );
$('#allowed4').val( "" );
$("#messagetable").load("messagetable.php");
$('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );
$('#messageform').show().submit( submitForm );
} else {
$('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
$('#messageform').delay(messageDelay+500).fadeIn();
}
}
</script>
<form id="messageform" action="message_forward.php" method="post">
<p>
<label for="ename">Event Name</label>
<input name="ename" type="text" id="ename" required="required">
</p>
<p>
<label for="message">Message</label>
<span id="sprytextarea1">
<textarea name="message" id="message" required="required"></textarea>
<span id="countsprytextarea1"> </span><span class="textareaRequiredMsg">A value is required.</span><span class="textareaMaxCharsMsg">Exceeded maximum number of characters.</span></span></p>
<p>
<label for="etype">Response Required</label>
<select name="etype" size="2" id="etype">
<option value="0" selected="selected">No</option>
<option value="1">Yes</option>
</select>
</p>
<div id="rtypeshow" style="display:none;">
Event Resender End Date:
<span id="sprytextfield1">
<input name="datepicker" type="text" id="datepicker" size="10">
MM/DD/YYYY <span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br>
Send Response To: <select name="eforward" id="eforward">
<?php
do {
?>
<option value="<?php echo $row_Recordset1['cphone']?><?php echo $row_Recordset1['provider']?>"><?php echo $row_Recordset1['fullname']?>-SMS Message via Cell Phone</option>
<option value="<?php echo $row_Recordset1['email']?>"><?php echo $row_Recordset1['fullname']?>-Email Message</option>
<?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
$rows = mysql_num_rows($Recordset1);
if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
}
?>
</select><br>
<label for="question">Question for responses</label>
<input type="text" name="question" id="question" maxlength="18"><br>
<label for="rtype">Response Type</label>
<select name="rtype" size="3" id="rtype">
<option value="0" selected="selected">Standard Yes/No Response</option>
<option value="1">Create Responses</option>
<option value="2">Get Users Own Response</option>
</select>
<div id="allowed" style="display:none;">
<h4>Response Options</h4>
<label for="allowed1">Option 1</label>
<input type="text" name="allowed1" id="allowed1" maxlength="12" placeholder="Required">Max Length = 12
<label for="allowed2"><br>
Option 2</label>
<input type="text" name="allowed2" id="allowed2" maxlength="12" placeholder="Optional">Max Length = 12
<br>
<label for="allowed3">Option 3</label>
<input type="text" name="allowed3" id="allowed3" maxlength="12" placeholder="Optional">Max Length = 12
<label for="allowed4"><br>
Option 4</label>
<input type="text" name="allowed4" id="allowed4" maxlength="12" placeholder="Optional">Max Length = 12
</div>
</div>
<input name="submit" type="submit" value="Send Messages">
</form>
Additional Comments:
Sending a message a second time seems to make it even worse then if the page is refreshed before sending another message.
It looks like your code is attaching the submitForm function multiple times to the submit handler.
In your submitFinished function you attach the handler again:
$('#messageform').show().submit( submitForm );
You can check this by refreshing the page then submitting the form. If it only submits once after refresh then multiple times after that you know that is the problem.

form not validating - javascript

bit of a noob with form validation. I'm trying to get this form to validate on the required fields, and something's amiss. Here's what I'm working with:
html:
<form action="../visit/thankyou.html" method="post" id="vsurvey">
<input type="hidden" name="id" value="503" />
<fieldset>
<legend>Group and Coordinator Information</legend>
<label><span>Group Leader Name<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8149" />
</label>
<label><span>Email<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8155" />
</label>
<label><span>Phone<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8156" />
</label>
<label><span>School/Organization<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8159" />
</label>
<label><span>Program</span>
<input type="text" name="question_8180" />
</label>
<label><span>Grade(s)</span>
<input type="text" name="question_8181" />
</label>
<label><span>Number of Participants<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8182" />
</label>
</fieldset>
<fieldset>
<label><span>Preferred Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8185" name="question_8185" />
</label>
<label><span>Second Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8186" name="question_8186" />
</label>
<label><span>Third Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8187" name="question_8187" />
</label>
<label>Special Accommodations
<input type="text" name="question_8174" />
</label>
</fieldset>
<label>What is the purpose or desired outcome of this visit?
<textarea name="question_13026"></textarea>
</label>
<label>How did you learn about our Group Visit Program?
<textarea name="question_8176"></textarea>
</label>
<label>Comments
<textarea name="question_8184"></textarea>
</label>
<input type="submit" id="sbutton" value="Submit Request" />
</form>
js:
function validateForm() {
var x = document.forms["vsurvey"]["question_8149"].value;
if (x == null || x == "") {
alert("Please fill in the Group Leader's name.");
return false;
}
var x = document.forms["vsurvey"]["question_8155"].value;
if (x == null || x == "") {
alert("Please fill in the email field.");
return false;
}
var x = document.forms["vsurvey"]["question_8156"].value;
if (x == null || x == "") {
alert("Please fill in the phone field.");
return false;
}
var x = document.forms["vsurvey"]["question_8159"].value;
if (x == null || x == "") {
alert("Please fill in the School/Organization field.");
return false;
}
var x = document.forms["vsurvey"]["question_8182"].value;
if (x == null || x == "") {
alert("Please indicate the number or participants.");
return false;
}
var x = document.forms["vsurvey"]["question_8185"].value;
if (x == null || x == "") {
alert("Please enter your preferred date.");
return false;
}
var x = document.forms["vsurvey"]["question_8186"].value;
if (x == null || x == "") {
alert("Please enter your second date preference.");
return false;
}
var x = document.forms["vsurvey"]["question_8187"].value;
if (x == null || x == "") {
alert("Please enter your third date preference.");
return false;
}
}
http://jsfiddle.net/blackessej/9a6BJ/1/
Currently the form submits the info anyway, but without sending the user to the thankyou page, if all required fields aren't filed in. If all required fields are filed, the thankyou page gets called.
You're not calling validatorForm. Your input button needs to be the following
<input type="submit" id="sbutton" value="Submit Request" onclick="return validateForm()" />
Or use the onsubmit event of your form
<form action="../visit/thankyou.html" method="post" id="vsurvey" onsubmit="return validateForm()">
You need to create an onSubmit event to call validateForm:
document.getElementById('vsurvey').onsubmit = validateForm;

Categories