I have two functions, the first checks to see if the terms and conditions checkbox has been checked and if at least one checkbox from a span class of events which each has a checkbox next to it has been checked, if both function conditions have been met then the disabled submission button should be enabled but it doesn't seem to work.
Code for the start of the form
<form id="bookingForm" name"form1" action="#" method="get">
code for the terms and conditions
<div id="ChangeTextScript">I have read and agree to the terms and conditions</div>
<input type="checkbox" id="termsChkbx" onclick= "goFurther(); changetext(this,'ChangeTextScript');">
Submit button code
<input type="submit" name="submit" value="Make booking" id="sub1" disabled=disable />
Javascript code
The 2 functions
function goFurther(){
if (document.getElementById("termsChkbx").checked == true) {
return true;
} else {
return false;
}}
function checkCheckboxes() {
if (document.querySelector('input[name="event\\[\\]"]:checked') >= 1 ) {
return true;
} else {
return false;
}}
The code that checks to see if both functions has been met then it should enable the button
if(checkCheckboxes() && goFurther()) {
return true;
document.getElementById("sub1").disabled = false;
} else {
document.getElementById("sub1").disabled = true;
}
I realize you asked this over two months ago, but in the case that you're still looking for an answer, the best way to accomplish this is via an onchange event handler attached to the form.
HTML
<form id="myform">
<span>
<input type="checkbox" id="cb1"> option 1
<input type="checkbox" id="cb2"> option 2
<input type="checkbox" id="cb3"> option 3
</span>
<div>
<input type="checkbox" id="tnc"> I agree to the Terms & Conditions.
</div>
<button id="disabled" disabled>submit</button>
</form>
JavaScript
document.getElementById("myform").onchange = function () {
document.getElementById("disabled").disabled =
!(document.getElementById("tnc").checked &&
( document.getElementById("cb1").checked ||
document.getElementById("cb2").checked ||
document.getElementById("cb3").checked ) );
}
The basic idea is to set the disabled property of the #disabled button to the negation of the following condition:
document.getElementById("tnc").checked && conditionB
where conditionB is equal to
document.getElementById("cb1").checked || document.getElementById("cb2").checked || document.getElementById("cb3").checked;
This only returns true when #tnc is checked, along with one of the input boxes in the span (#cb1, #cb2, or #cb3). That means the .disabled property is equal to !true (aka false) when the aforementioned requirements are met.
fiddle
If this is the only thing you need to do, you could encapsulate the code that checks the functions in a while loop. Also, I see that you return true before the button is enabled. This stops execution of the function while returning true. You would like to place this return statement after the button is enabled.
Related
i'm triyng to validate a form.
In this form you've to choose at least one element by checkboxes, and I can't be sure about their quantity (it depends by elements number).
I need to enable the submit input if one or more checkboxes are checked, and disable it if there aren't any checkbox checked, how can I do?
Here's my code:
<form id="booking">
<input type="checkbox" name="room1" class="roomselect"/>
<input type="checkbox" name="room2" class="roomselect"/>
<input type="checkbox" name="room3" class="roomselect"/>
<input type="submit" value="Request" id="subm" />
</form>
//dom ready handler
jQuery(function ($) {
//form submit handler
$('#booking').submit(function (e) {
//check atleat 1 checkbox is checked
if (!$('.roomselect').is(':checked')) {
//prevent the default form submit if it is not checked
e.preventDefault();
}
})
})
You can use :checked selector along with .length to find checked checkbox count:
var len = $(".roomselect:checked").length;
if(len>0){
//more than one checkbox is checked
}
Demo
The :checked selector will Match all elements that are checked or selected.
You could try this
$("#subm").click(function(e){
if($(".roomselect:checked").length == 0){
e.preventDefault();
}
});
i suggest you to use "button" instead of "submit".
please follow this
HTML->
<form id="booking" action="https://www.google.co.in/search">
<input type="checkbox" value="facebook" name="q"/>
<input type="checkbox" value="gmail" name="q"/>
<input type="checkbox" value="stackoverflow" name="q"/>
<input type="button" value="Request" id="submit" />
$(function(){
$("#submit").click(function(e){
var number_of_checked_checkbox= $("input[name=q]:checked").length;
if(number_of_checked_checkbox==0){
alert("select any one");
}else{
$("#booking").submit();
}
});
});
Vanilla JavaScript equivalent of the jQuery way, using document.querySelector
if (document.querySelector('.roomselect:checked')) {
// somethings checked
}
Demo
The easiest method would be with javascript, fortunately someone's already done all the work here (with jQuery). All you'd need to do to adapt that example is to change #form_check to #booking.
Essentially what that example is doing is forcing itself before the submit action when it sees one is being tried for the form then it's searching inside the form element for any checkbox elements with a checked state and if it can't find any is sending a preventdefault to stop whatever the client/browser's default response to a submit action request would be or otherwise just sending as normal.
Also regarding the other answers, using === is more secure and returning false gives you some redundancy. Here's some discussion on what the return false adds.
Additionally don't use click() for this as you potentially run into use cases where you're technically submitting the form but aren't actually clicking it, like say when you hit enter
try this
var checked = false;
$(function(){
$('#subm').click(function(e){
checkall();
if(!checked){
e.preventDefault();
}
});
$('.roomselect').change(function(e){
checkall();
});
checkall();
});
function checkall()
{
checked = $('.roomselect:checked').length > 0;
$('#subm').prop('disabled',!checked);
}
$("#form_id").submit(function(e) {
var totalChecked = $('#div_id:input[type="checkbox"]:checked').length;
if(totalChecked < 1)
{
alert('Please select at least one checkbox before submit');
return false;
}
});
<input type="checkbox" value="On" name="policy" id="policy"></font>
<b><font face="Verdana" color="#ff0000" size="1">*</font></b>By checking the box, you are verifying with your digital signature that you have read and agree to all terms and conditions of the FEG agent agreement.
</td>
</tr>
<tr class="gr">
<td class="rowdot_lno">Do you agree?:</td>
<td class="rowdot_lno">
<input type="checkbox" value="On" name="iagree" id="iagree">
<b><font face="Verdana" color="#ff0000" size="1">*</font></b>I understand that I will be charged $24.95.
</td>
</tr>
I have a <form method="post" action="enroller.dhtml" name="mainform" onSubmit="update_prices()"> and a button <input type="submit" value="Continue">
I've tried a few things but to no avail. The form can be submitted without the checkboxes being checked. Here's the latest bit of jQuery I've tried.
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')) {
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
Also I found this on fiddle but it's not really working.. I tried to customize it to my needs.
http://jsfiddle.net/shryme/D3Ldj/
If you have an onSubmit on your submit button or add it though jquery, call a function which would :
if ($('input[type=checkbox] :checked').length == 0) {
alert("Please select at least one to upgrade.");
return false;
} else { return true; }
I hope this is what you are looking for.
From this line:
Please select at least one to upgrade
It seems that you need at least one checkbox checked. If that is the case, you could do something like this:
$("form").submit(function(){
var length = $("input[type=checkbox]").not(":checked").length;
if (length > 1) {
alert("Please select at least one to upgrade.");
return false;
}
});
Which checks to see how many checkboxes are not checked, determines if that number is less than the required number, and if it is, triggers the error message.
You can also further simplify the length variable if you are comfortable with CSS selectors:
var length = $("input[type=checkbox]:not(:checked)").length;
Here's an example.
I would suggest to do it with some MVVM framework but here's some code to do it with jQuery. I made it so that the submit button is disabled unless both boxes are checked.
Fiddle with 2 checkboxes and a submit button
function areChecked(){
var is_1_checked = $('#check_1').is(':checked');
var is_2_checked = $('#check_2').is(':checked');
return is_1_checked == is_2_checked == true;
}
function enableButton(val){
$('#submit').attr('disabled', false);
}
$('#check_1').on('click', function(){
if (areChecked())
enableButton(false);
});
$('#check_2').on('click', function(){
if (areChecked())
enableButton(false);
});
I need help validating radio buttons with JavaScript. Here's the section of HTML:
<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" /> Yes, both!<br/>
<input type="radio" name="receptionattend" value="yesc" /> Yes, but only the ceremony! <br/>
<input type="radio" name="receptionattend" value="yesr" /> Yes, but only the reception!<br/>
<input type="radio" name="receptionattend" value="no" /> No, you guys are lame!
And here's the simplest validation code I have:
function validateForm()
var y=document.forms["rsvpform"]["receptionattend"].checked;
if (y==null || y=="")
{
alert("Please indicate whether or not you will attend.");
return false;
}
}
My issue mostly seems to be that, no matter how I code the validation, it returns an error message even when I have a radio button selected.
The first issue you have is that in general, you should force a default in your radio buttons, make one of the buttons be already "checked" and you will never have a null value passed to your form checker. Most people expect their radio buttons to have a default already checked and this is standard practice in web development.
However, should you need to check for null or undefined, you should use typeof and strict comparison with ===
(typeof y === "undefined" || y === null);
After reading your comment - I noticed one other thing. Are you trying get get the value directly from Javascript by reading the DOM with like an onclick function? You won't be able to do this because you aren't ever actually getting your checked value with this line.
var y=document.forms["rsvpform"]["receptionattend"].checked;
Instead, try something like this.
var y = document.getElementsByName('receptionattend');
var y_value;
for(var i = 0; i < y.length; i++){
if(y[i].checked){
y_value = y[i].value;
}
}
y_value should now return the result of the checked radio button. If nothing was checked y_value will be null.
this line:
var y=document.forms["rsvpform"]["receptionattend"].checked;
returns either true or false based on checked attribute of your element, so you should be doing:
if ( !y ) { //if not checked i.e false
alert("Please indicate whether or not you will attend.");
return false;
}
do like:
function validateForm() {
var is_checked = false;
var eles = document.forms["rsvpform"]["receptionattend"];
for(var i = 0; i < eles.length; i++ ) {
if( eles[i].checked ) {
is_checked = true;
break;
}
}
if (!is_checked)
{
alert("Please indicate whether or not you will attend.");
return false;
}
else {
alert("valid");
}
}
Demo:: jsFiddle
I'm not going to suggest using jquery just for this. But should you end up using jquery, it makes this kind of validation very easy.
HTML Note the use of Labels, this is just a good practice, it means your uses can click on the text and a whole raft of other accesibililty bonuses.
<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" id="rcBoth" /><label for="rcBoth">Yes, both!</label><br/>
<input type="radio" name="receptionattend" value="yesc" id="rcCOnly" /><label for="rcCOnly"> Yes, but only the ceremony! </label><br/>
<input type="radio" name="receptionattend" value="yesr" id="rcROnly" /><label for="rcROnly">Yes, but only the reception!</label><br/>
<input type="radio" name="receptionattend" value="no" id="rcNo" /><label for="rcNo"> No, you guys are lame!</label><br />
<input type="button" value="Validate Me" id="btnValidate"/>
Javascript/Jquery Wire this up in the jquery $(document).ready event.
$("#btnValidate").click(function(){
//The following selector is not very efficient, classes
//or a bounding element (eg div or fieldset) would be better
if($("input[name='receptionattend']:checked").length == 0)
{
alert("Please tell us if you're attending or not!");
}
});
http://jsfiddle.net/wpMvp/
To break down the script
$("#btnValidate").click(function(){}); adds an onlclick event handler to the button with ID btnValidate
$("input[name='receptionattend']:checked").length returns how many input elements with a name of receptionattend are checked
the rest should be fairy self explanatory
I need to use javascript so that when the one radio button is selected nothing happens but if the other one is (for example, other address) it will then validate the following fields;
street
suberb
postcode
Whilst I post this, it's probably a similar method, but when I have a checkbox and a textbox how could I make it so that the textbox must not be left empty only if the checkbox is checked...
Thanks everyone!!!! Ask for more details if needed, I'm terrible at explaining things!
/* To check radio validation in Employee Details page */
function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
{
window.open("EditEmployee`enter code here`.html","_self");
}
return false;
}
Hope this example helps you friend.
Since they will be checking the radio button when they click on it, you can add an onClick event to one of the radio buttons and not the other.
<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>
For the checkbox, when a user checks the box you should set the focus to the text input field. That way if a user moves away from that field (onBlur) you can give them an error/alert to fill in the text.
<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>
<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
I'll assume you might be using jQuery, since you didn't say. If not, then you can still take the concepts and port them to plain old javascript or whatever you're using.
Example markup
<form id="address-form">
<input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
<input type="radio" name="validate" value="no"> Don't Validate<br>
Street <input name="street"><br>
Suberb <input name="suberb"><br>
Postcode <input name="postcode"><br>
<input type="submit">
</form>
Conditional validation
Either somewhere on your page in a <script> tag or in a javascript file you include, create a submit event that will check the value of the radio input before doing the validation.
$('#address-form').submit(function(event) {
if ($('input[name=validate]:checked').val() === 'yes') {
if (!formValid()) {
event.preventDefault(); // Don't submit the form
}
}
});
// Perform validations
function formValid() {
if ($('input[name=street]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=suberb]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=postcode]').val().length == 0) {
// tell them ...
return false;
}
return true;
}
That should do the trick!
I created a jsfiddle you can mess with further if you want - http://jsfiddle.net/nilbus/JNnuX/2/
Using a checkbox instead
It's pretty similar to use a checkbox. Instead of this
if ($('input[name=validate]:checked').val() === 'yes') {
just check to see if your checkbox is checked.
if ($('input[name=validate]').attr('checked')) {
http://jsfiddle.net/nilbus/JNnuX/3/
I am using below method for validating that one of radio button must be selected.
function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
alert('Please select search type');
return false;
}
return true;
}
In above method searchType is radio button which is creating two buttons. It works fine that is shows alert message if none of the two radio buttons are selected but it show alert message even when second of the radio button is selected. Any idea please?
<html>
<head>
<script language="javascript">
function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
alert('Please select search type');
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1">
<input type="radio" name="form1:searchType" /> male
<input type="radio" name="form1:searchType" /> female
<input type="submit" name="submit" value="submit" onclick="validateForm()" >
</form>
</body>
</html>
i am using your function in this code and its working fine, it may help you
You need to use the or operator, not and - when using && it will be true only when both conditions are true - when one of them is false the whole statement is false as well.
So, just change to:
if(a || b){
alert('Please select search type');
return false;
}
And it should do what you want.
Edit: sorry, got confused myself with the boolean logic.
From quick test your code does work exactly as-is: only when no checkbox is ticked the alert shows up.
Please explain what is the problem and steps to reproduce in the jsFiddle if possible and we'll see.