Need help validating radio buttons with JavaScript - javascript

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

Related

document.forms.value returning "undefined" only in IE

So I've got a form. In this form I've got a radio button:
<span>
<label>
<input type="radio" name="mature" value="0">
All Ages
<span class="checkmark"></span>
</label>
<label>
<input type="radio" name="mature" value="1">
18+
<span class="checkmark"></span>
</label>
</span>
However, in my JS validation for this form, I noticed that in Internet Explorer, this radio button would always return an error.
if (document.forms["imageSubmit"]["mature"].value == "" || document.forms["imageSubmit"]["mature"].value == null) {
alert(document.forms["imageSubmit"]["mature"].value);
return false;
}
So for example in this case, the alert will always return "undefined". But, again, only in internet explorer.
Why is this happening?
Edit:
Thank you for the redirect. I've adjusted my code like so:
var mature = document.getElementsByName('mature');
var matureValue = false;
for(var i=0; i<mature.length;i++){
if(mature[i].checked == true){
matureValue = true;
}
}
if(!matureValue){
alert("Please fill the Viewing Restrictions field.");
return false;
}
You have multiple elements with the same name.
document.forms["imageSubmit"]["mature"] is a collection, not a single element.
You need to loop over it (like an array) until you one the one with the true checked property.
In HTML 5, radio buttons are special cased so a collection of them will have its own value property representing the currently checked radio button. Internet Explorer is too old to support this feature.

javascript disabling form submission until functions are true

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.

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

JavaScript Radio button selection validates fields?

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/

Radioboxes and JQuery

Here's my HTML code:
<label><input type="radio" id="fNuttig" /> Nuttig</label>
<label><input type="radio" id="fNietNuttig" /> Niet nuttig</label>
<label><input type="radio" id="fNogUitTeMakenNuttig" />Nog uit te maken</label>
And here's my javascript code:
if ($('#fNuttig').val() == 'on') {
nuttig = 'Nuttig';
} else if ($('#fNietNuttig').val() =='on') {
nuttig = 'Niet nuttig';
} else if ($('#fNogUitTeMakenNuttig').val() =='on') {
nuttig = 'Nog uit te maken';
} else {
nuttig = 'ongeldige invoer';
}
alert($('#fNuttig').val()); // Gives 'on'
alert($('#fNietNuttig').val()); // Gives 'on'
alert($('#fNogUitTeMakenNuttig').val()); // Gives 'on'
alert(nuttig); // Gives 'on'
This code gets called when pressing a button.
Why are all my radiobuttons turned on? If I add the 'name=' tag, and accomplish the same using PHP, it does work, and in javascript, it says that my buttons are always 'on'.
What am I doing wrong?
Yvan
You want to use if ( $('#fNuttig').is(':checked') ) instead of if ( $('#fNuttig').val() == 'on' ).
$('#fNuttig').val() is just retrieving the value of the value attribute, whether it's checked or not. $('#fNuttig').is(':checked') will return true if it's checked and false if it's not.
Your HTML code lack of name attribute. It's mandatory for a input element to have them. Radios with same name will only able to turn on one of it. any particular reason why you write the js code like the above?
It's better to access it by name
<input name="radio" .../>
$('input[name="radio"]').val();

Categories

Resources