I need to figure out how to check that my radio buttons are all filled. This is what I have but it only checks one button
var btns = form.choice_1;
for (var i=0; el=btns[i]; i++) {
if (el.checked) return true;
}
alert('Please select a radio button');
return false;
This is the form that I am taking input from.
<form onsubmit="return checkRadios(this);" name = "form" action = "like.php" method ="post" >
<h1> Questions </h1>
<p> Question 1 </p>
<input type="radio" name="choice_1" value="1">Like <input type="radio" name="choice_1" value="2" > Dislike
<p> Question 2 </p>
<input type="radio" name="choice_2" value="1">Like <input type="radio" name="choice_2" value="2" > Dislike
<p> Question 3 </p>
<input type="radio" name="choice_3" value="1">Like <input type="radio" name="choice_3" value="2" > Dislike
<p> Question 4 </p>
<input type="radio" name="choice_4" value="1">Like <input type="radio" name="choice_4" value="2" > Dislike
<br> <br>
<input type="submit" value="Submit">
Any help is appreciated.
Try this:
var checkRadios = function () {
var btns = form.querySelectorAll('input[name^=choice_][type="radio"]');
for (var i = 0; i < btns.length; i = i + 2) {
var check = true;
if (!btns[i].checked && !btns[i + 1].checked) check = false;
}
if (!check) alert('Please select a radio button');
return check;
}
var form = document.querySelector('form[name="form"]');
form.onsubmit = checkRadios;
Fiddle
You should use jQuery for this. It makes it much easier.
You would do it like this:
var e = ('#[[[[id of your radio]]]]');
if($e.is(':checked'){
//do what you need to
};
Try this. You will need jQuery.
checkRadios = function() {
if $("input:radio :checked").length == 0 {
alert('Please select a radio button');
return false;
}
}
Related
I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />
On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.
I have many server input checkboxes. I have given the first checkbox the id all. By default it will be checked. When the user checks other checkboxes, then checkbox with id all will be unchecked. And if all is checked other checkboxes will be unchecked. For this to happen i made the code but nothing is happening.
Here is what i have tried.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check()" checked/>ALL <br/>
<input type="checkbox" id="servers" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" id="servers" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" id="servers" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" id="servers" value="amp" name="server[]" onChange="check()" />AMP <br/>
</form>
function check(){
var all = document.getElementById("all"),
group = document.getElementById("servers");
if(all.checked == true){
group.checked == false;
}elseif(group.checked == true){
all.checked == false;
}
}
I wanted my code to work like THIS.
I dont want to use jQuery for some reasons. So i need my code to be in pure JS.
Any help will be appreciated.
You can't use the same ID on multiple elements.
Try this, notice how I placed the checkboxes in a div
Here it is working: http://jsfiddle.net/Sa2d3/
HTML:
<form>
<div id="checkboxes">
<input type="checkbox" id="all" value="all" name="all" onChange="check()" />ALL <br/>
<input type="checkbox" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" value="amp" name="server[]" onChange="check()" />AMP <br/>
</div>
</form>
JavaScript:
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// loop through all the inputs, skipping the first one
for (var i = 1, input; input = inputs[i++]; ) {
// Set each input's value to 'all'.
input.checked = el.checked;
}
}
// We need to check if all checkboxes have been checked
else {
var numChecked = 0;
for (var i = 1, input; input = inputs[i++]; ) {
if (input.checked) {
numChecked++;
}
}
// If all checkboxes have been checked, then check 'all' as well
inputs[0].checked = numChecked === inputs.length - 1;
}
}, false);
EDIT:
Based on your request in the comment here is the updated javascript:
http://jsfiddle.net/T5Pm7/
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// If 'all' is checked
if (el.checked) {
// Loop through the other inputs and removed the check
for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
}
}
}
// If another has been clicked, remove the check from 'all'
else {
inputs[0].checked = false;
}
}, false);
You can only assign the same id to one element. What you want to do is give them a class="servers" and then use document.getElementsByClassName("servers"); in your JavaScript.
You cannot have same id for multiple HTML elements. You could do something like this to achieve what you are asking for.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check(this, 'a')" checked/>ALL <br/>
<input type="checkbox" id="servers1" value="xampp" name="server[]" onChange="check(this, 's')" />XAMPP <br/>
<input type="checkbox" id="servers2" value="wamp" name="server[]" onChange="check(this, 's')" />WAMP <br/>
<input type="checkbox" id="servers3" value="mamp" name="server[]" onChange="check(this, 's')" />MAMP <br/>
<input type="checkbox" id="servers4" value="amp" name="server[]" onChange="check(this, 's')" />AMP <br/>
</form>
<script>
function check(cb, type){
var all = document.getElementById("all");
if (type == "a" && cb.checked){
var els = document.getElementsByName("server[]");
for(var i = 0; i < els.length; ++i)
els[i].checked = false;
} else if( type == "s" && cb.checked) {
all.checked = false;
}
}
</script>
put this function
function jvcheck(id,Vale){
Checkboxesclass = '.group'+id;
$(Checkboxesclass).each(function() {
this.checked = Vale;
});
}
and then put this code in your main checkbox
jvcheck('group222',this.checked);
all checkbox with class group222 now checked .
I have a simple multiple question form, each question has 4 answers and users must select 1 answer for each question.
So far I can check for an unanswered question and show an error message.
But now if all questions have been answered, I need the form to go to a results page (I assume window.location?)
How can I check if all questions have been answered?
$('.submit-button').click(function(event){
$('.validate-message').hide();
for (var i=1;i<6;i++) {
var input = $("input[name=q"+i+"]");
var inputChecked = $("input[name=q"+i+"]:checked");
if (!inputChecked.val()) { //if an answer is not selected for a question
$(input).parents('fieldset').append('<div class="validate-message" style="color:red;">Please choose an answer!</div>');
} else { // if an answer is selected for a question
}
}
return false;
});
Just use a boolean variable:
$('.submit-button').click(function(event){
var noErrors = true; // default to no errors
$('.validate-message').hide();
for (var i=1;i<6;i++) {
var input = $("input[name=q"+i+"]");
var inputChecked = $("input[name=q"+i+"]:checked");
if (!inputChecked.val()) { //if an answer is not selected for a question
noErrors = false; // an error was found, set noErrors to false
$(input).parents('fieldset').append('<div class="validate-message" style="color:red;">Please choose an answer!</div>');
} else { // if an answer is selected for a question
}
}
if(noErrors) // do stuff
return false;
});
Out of interest, here's a plain javascript solution.
Assuming HTML something like the following:
<form id="f0" onsubmit="return validateForm(this);">
<div>
<p>Question 1.<br>
A<input type="radio" value="A" name="q1"><br>
B<input type="radio" value="B" name="q1"><br>
C<input type="radio" value="C" name="q1"><br>
D<input type="radio" value="D" name="q1"><br>
</p>
<p>Question 2.<br>
A<input type="radio" value="A" name="q2"><br>
B<input type="radio" value="B" name="q2"><br>
C<input type="radio" value="C" name="q2"><br>
D<input type="radio" value="D" name="q2"><br>
</p>
<input type="reset" value="Clear answers">
<input type="submit" value="Submit answers">
</div>
</form>
A function to validate that each question has been answered is:
function validateForm(form) {
var control, controls = form.elements;
var visited = {};
var name, radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
name = control.name;
if (control.type == 'radio' && name && !visited.hasOwnProperty(name)) {
visited[name] = false;
radios = form[name];
for (j=0, jLen=radios.length; j<jLen; j++) {
visited[name] = visited[name] || radios[j].checked;
}
if (!visited[name]) {
// Question hasn't been answered, cancel submit and do whatever
alert('There are unanswered questions for ' + name);
return false;
}
}
// Validation for other controls
// ...
}
}
I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail