How to validate a radio button? - javascript

I am trying to validate a set of radiobuttons that output a message upon submit informing the user that they must make a selection before they continue. The code below never recognises that the buttons are checked and always outputs the alert message. How would I adapt this code to make it work?
Radiobuttons:
<input type="radio" name="examtype" value="GCSE"onclick="return confirmation();"/>GCSE
<input type="radio" name="examtype" value="AS" onclick="return confirmation();"/> AS
<input type="radio" name="examtype" value="A2" onclick="return confirmation();"/> A2 </td> </tr>
Function for confirmation onclick:
function confirmation() {
for (var i=0; i < document.ExamEntry.examtype.length; i++)
{
if (document.ExamEntry.examtype[i].checked)
{
var answer = confirm(document.ExamEntry.examtype[i].value)
if (answer){
document.ExamEntry.examtype[i].checked = true;
}
else{
document.ExamEntry.examtype[i].checked = false;
}
}
}
}
Code currently being used for rejecting unselected radiobuttons:
if (document.ExamEntry.examtype.checked){
alert('checked') //for testing if statement runs when appropriate//
}
else {
msg+="You must enter the exam type \n";
result = false;
}

Try setting a variable as false outside both functions, and then if the confirmation function runs, assign that variable to true.
Then in your next function where you check if the user have clicked a radio button or not, use an if statement that runs only if the variable has been set to false which could include your alert message.
Hope this helps :)

Here's an example code on how to validate radioboxes: http://jsfiddle.net/jyUAM/3/
<script type="text/javascript">
function validateRadioboxesByName(form, name)
{
var el = form[name];
for (i = 0; i < el.length; ++i) {
if (el[i].checked)
return true;
}
return false;
}
function checkRegistration() {
var isValid = validateRadioboxesByName(document.forms.test, "examtype");
if (!isValid)
alert("Please check one of the radiobox.");
return isValid;
}
</script>
<form name="test" onsubmit="return checkRegistration()">
<input type="radio" name="examtype" value="GCSE"/>GCSE
<input type="radio" name="examtype" value="AS"/> AS
<input type="radio" name="examtype" value="A2"/> A2
<button type="submit">Send</button>
</form>
This way you don't need to remember the state of a clicked radiobox, but just ask the browser when you need the data, that is, before submitting the data.
This tutorial may give you more ideas on how to visualize the message to the user instead of using an ugly alert call: http://www.the-art-of-web.com/html/html5-checkbox-required/
That the examples on the last link are for checkboxes shouldn't scare you, you can easily apply the same to radio- input-boxes and the like.

Related

need help about Php or Javascript Validation

I dont know how to do a self validation within the page.
I have a php file contains a checkbox and a lot of textboxes. What i would like to do is that, what the user will check on the checkbox will require the textboxes to be filled up. I tried to validate using my statement in php but it always redirect to another page before it validates everything, what i want is that when the user click the submit button, it will trigger the whole page and validate those that should be filled up.
user will check any of the checkbox
then it has a corresponding condition that will make the textboxes required to be filled in!
Hope you guys can help me. I dont know how to do it. javascript or anything? I need solution and show me please.
Codes are like this:
Test 1 <input name="chkbox[]" type="checkbox" value="1"><br>
Test 2 <input name="chkbox[]" type="checkbox" value="2"><br>
Test 3 <input name="chkbox[]" type="checkbox" value="3"><br>
Test 4 <input name="chkbox[]" type="checkbox" value="4"><br>
Test 5 <input name="chkbox[]" type="checkbox" value="5"><br>
<br><br>
Name <input name="txt1" type="text"><br>
Address <input name="txt2" type="text"><br>
Number <input name="txt3" type="text"><br>
Age <input name="txt4" type="text"><br>
Two options for this (all in javascript).
The first, as requested is validating when the user tries to submit.
document.addEventListener("DOMContentLoaded", function (event) {
var isValid = false;
document.querySelector("#formid").addEventListener("submit", function(e){
var _selector = document.querySelectorAll('input[type=checkbox]:checked');
var checked = _selector.length;
for(var i = 0; i<checked; i++){
if (_selector[i].checked) {
if(!document.querySelector('input[name=txt'+ _selector[i].value +']').value)
break;
}
}
if(checked == i)
isValid = true;
if(!isValid){
alert('at least one field is empty');
e.preventDefault(); //stop form from submitting
}
});
});
the second uses an eventlistener to add and remove the required field.
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i<_selector.length; i++){
_selector[i].addEventListener('change', function (event) {
if (event.target.checked) {
document.querySelector('input[name=txt'+ event.target.value +']').required = true;
} else {
document.querySelector('input[name=txt'+ event.target.value +']').required = false;
}
});
}
});
Then you can style the required fields to show which needs to be filled:
:required{border: red solid 1px;}

Javascript: redirect to new page based on radio button choice

What I am trying to do is redirect to a new page if the "yes" button is clicked. I already have a prompt set up if they click "no". However, there is a form (name and email) that needs to be filled out for this to work. If they do not fill out these details, I want a prompt to arise telling the user that they need to fill them out before they can proceed.
I am fairly new to javascript so any tips or explanations would be greatly appreciated.
Below is the html code
<input type="radio" name="radio" id="yes"><strong>Yes, I agree.</strong>
<br>
<input type="radio" name="radio" id="no" checked="checked"><strong>No, I do not agree. </strong><br>
<br>
If you agree, please enter your full name and email address in the spaces below and press submit.
<br>
<form> Full Name:<input type="text" name="fullname"></form>
<br>
<form> Email Address:<input type="text" name="email"></form>
<br>
<br>
<form action="endPage.jsp" id="form">
<input type="submit" id="submit" value="Submit" name="submit" />
</form>
And the javascript code
var submitBtn = document.getElementById("submit");
var termsChk = document.getElementById("yes");
var formFrm = document.getElementById("emailField");
var formFrm = document.getElementById("nameField");
submitBtn.addEventListener("click", function() {
if (termsChk.checked === true && formFrm)
{
alert("Checked!");
formFrm.submit();
} else {
alert("Please Contact Spearhead Mining Corporation: projects#spearheadmining.com to discuss your options for project submittal!");
}
return false;
});
Use window.confirm() with the spcific message to user and use window.location() to redirect to the new url.
result = window.confirm("Message to user");
if(result) {
window.location = "new url";
} else {
//do the rest of logic
}
For a more specific answer it might help if you posted the code for yes and no buttons, as well as the HTML code for the form. That being said the way you would generally handle this is in the code for the yes button you run whatever client side validations you need to run, in this case checking if the name and email fields aren't empty, then displaying your error message instead of redirecting if everything is not valid.
For instance in your yes handler
if(document.getElementById('emailField').value == null || document.getElementById('namefield') == null){
/*error handling code goes here*/
return
}
else{
/*redirection code goes here*/
}

Checkbox js toggling incorrectly

I have a check box in my registration form like this:
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate('tos')" name="tos"/>
</form>
And I am using JS to check if its ticked, and if so, display a green tick in the form. However, its not actually ticking the check box when its clicked but it is loading the green tick.
Additionally, clicking it a second time doesn't remove the green tick which it should, because the user effectively unticked the check box.
So my JS is this:
function validate (type){
output = [];
var x = document.getElementById("reg");
if (type == 'tos'){
div = 'result_tos';
input = x.elements[4].checked;
if (input){
output.push('<img src="correct.png"/>');
} else {
output.push('You must agree to our terms of service in order to join !');
}
document.getElementById(div).innerHTML = (output.join('')); //display result
}
}
The following jsfiddle is a slightly modified version of your code that seems to be working fine. I don't think your error is here. (I'm not familiar with elements; is that IE specific? I changed that to work on other browsers.)
http://jsfiddle.net/QnDAg/1/
I would approach this as below. Pass a reference to the element from the listener.
<form name="reg" id="reg" method="post">
<input type="checkbox" onclick="return validate(this)" name="tos">
</form>
<script type="text/javascript">
function validate(el) {
// you don't really need a reference to the form,
// but here's how to get it from the element
var form = el.form;
if (el.name == 'tos') {
if (el.checked) {
// show pass graphic (green tick?)
} else {
// hide checkbox and show text
}
}
}
</script>
Swapping between displaying the tick and text should be done by setting a class value, that way you can change it to whatever you want in the markup and the script just toggles the two.
This is probably how I would suggest you do this, which is more complex than the example given, but I'm struggling a little bit with the intended flow and the flow the OP is using:
Mock HTML
<form name="reg" id="reg" method="post">
<input type="checkbox" id="agree" name="agree"/> Agreement<br/>
<input type="checkbox" id="ok" name="ok"/> Ok<br/>
<input type="checkbox" id="tos" name="tos"/> TOS<br/>
<button name="submit" type="submit">Submit Validation</button>
</form>
<h1>Display Output</h1>
<div id="display"></div>​
Iterating Validation
function validate (){
var display = document.getElementById('display'),
output = [],
checks = ['agree','ok','tos'],
check,
msg;
while (check = document.reg[checks.pop()]) {
if (!check.checked) {
switch (check.name) {
case 'agree':
msg = 'You must AGREE!';
break;
case 'ok':
msg = 'You must OK!';
break;
case 'tos':
msg = 'You must TOS!';
break;
}
output.push(msg);
}
}
if (output.length == 0) {
output = [
'You have successfully validated!',
'<img src="http://goo.gl/UohAz"/>'
];
}
display.innerHTML = output.join('<br>');
return false;
}
And don't forget the window.onload when you attach the event handler. Below isn't necessarily the preferred preferred method, but it's cleaner than inline handlers like onclick="validate()".
window.onload = function(){
document.reg.onsubmit = validate;
};
http://jsfiddle.net/bj5rj/2

jquery validation

I have a poll with a couple a questions. Here is html code
<form id="pool">
<div class="questions>
<input type="radio" name="sex">Male
<input type="radio" name="sex">Female
</div>
<div class="questions>
<input type="radio" name="hair">Brown
<input type="radio" name="hair">Blonde
</div>
.... a lot of qestions div's
</form>
What to do so after the form is submitted to be sure that there is a checked radio button in all div`s ?
If you know how many groups you have you can just do:
if($('#pool input:radio:checked').length < numGroups){
// At least one group isn't checked
}
Otherwise you need to count the number of groups first. I can't think of any way to do this better then:
var rgroups = [];
$('#pool input:radio').each(function(index, el){
var i;
for(i = 0; i < rgroups.length; i++)
if(rgroups[i] == $(el).attr('name'))
return true;
rgroups.push($(el).attr('name'));
}
);
rgroups = rgroups.length;
if($('#pool input:radio:checked').length < rgroups)
alert('You must fill in all the fields.');
else
alert('Thanks!');
set default values or create handler for submit button and check if some values was checked. If no radio button is checked, show error message and do not submit form ( return false)
Untested code, but this is the idea:
if($('#pool').children().length == $('pool
div').find('#pool input:radio:selected').length) {
//do stuff
}
You can use the jquery validate plugin
from my experience this plugin is very efficient

JavaScript function checked if a radio button is selected

<label for="Merital Status">Marital Status:</label>
<input type="radio" title="Marital Status" name="Marital_Status" id="Marital Status" value="Single"/>Single
<input type="radio" title="Marital Status" name="Marital_Status" value="Married"/>Married
<input type="radio" title="Marital Status" name="Marital_Status" value="Divorced"/>Divorced
And I want to write a JavaScript function that checks whether a radi button named "Merital_Status" is selected. I represent the function that I wrote for this purpose. The function gets as an argument the element id and returnes boolen:
function radio_button_checker(elemId)
{
var radios = document.getElementsByTagName(elemId);
var value = false;
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
value = true;
break;
}
}
return value;
}
And I invoke this function like this:
if (radio_button_checker('Marital_Status') == false)
{
alert('Please fill in your Merital Status!');
return false;
}
But it does not work. Please tell me how to modify my function in order to check if radiobutton is checked.
What you are doing is looking for an element with the tag name "Merital_Status". Replace document.getElementsByTagName with document.getElementsByName and it should work.
You are mixing ID's and NAME's.
Your radio button "set" needs to all have the same name (which you have), and if you need to refer to them individually by id, then you'll need to add an id to the last two (currently not set... and not required if you apply the labels to each individual option). You will want the label tags for each radio button as it improves the usability by allowing the user to click on the word not just the small radio button.
Marital Status:
<label><input type="radio" name="Marital_Status" value="Single"/>Single</label>
<label><input type="radio" name="Marital_Status" value="Married"/>Married</label>
<label><input type="radio" name="Marital_Status" value="Divorced"/>Divorced</label>
However when you test... you want to see that at least 1 radio in the set is checked. You can do this with:
function radioButtonChecker(fieldNAME){
var radioSet = document.forms[0].elements[fieldName];
for(var i=0;i<radioSet.length;i++){
if(radioSet[i].checked){
return true;
}
}
return false;
}
There are a few presumptions made here.
You always have more than 1 radio button in the set
Your form is the 1st (index 0) form... if not you'll need to adjust the radioSet lookup

Categories