Checking all radio button are checked in native javascript - javascript

I have a gatherRadioBtn() function which posts form else displays error in page. This takes cue from checkRadioWrapper() to check if all radio buttons are checked.
However, the true condition does not materialize. Is there a mistake in my (r[i].type == "radio") && !(r[i].checked) expression.
Will upload on jsfiddle soon
Thanks.
function checkRadioWrapper()
{
for (var i=0; i < r.length; i++)
{
if ( (r[i].type == "radio") && !(r[i].checked) )
{
return false;
}
}
return true;
}
function gatherRadioBtn()
{
alert("in gather");
var r = document.getElementsByTagName("input");
var literal = [];
for (var i=0; i < r.length; i++)
{
if ( (r[i].type == "radio") && r[i].checked )
{
literal.push(r[i].name);
literal.push(r[i].value);
}
}
if (checkRadioWrapper())
{
document.getElementById("Errnodata").innerHTML = "" ;
var joinedArray = literal.join(", ");
window.opener.document.getElementById("myarray").value= joinedArray;
window.opener.getVolunteerDetails();
window.close();
}
else
{
document.getElementById("Errnodata").innerHTML = "Please select for every radio btns!" ;
}
}

You'll have to pass "r" as a parameter to your function:
function checkRadioWrapper( r )
{
for (var i=0; i < r.length; i++)
// etc
and then:
if (checkRadioWrapper( r ))
Now, that said, in a group of radio buttons sharing the same name, the browser will never allow all of them to be checked at the same time. Thus, this really doesn't make a lot of sense. If you've got radio buttons that don't share a name with other radio buttons, they should be checkboxes and not radio buttons.

Related

IT Quiz - do not show anwers unless checkbox is selected

I am trying to make sure that at least two checkboxes are selected. If no checkboxes are selected, then an error message appears. This is what I have tried so far:
function quiz4() {
var a4 = document.getElementsByName('q4');
for (i = 0; i < a4.length; i++) {
if(a4[i].checked == false) {
document.getElementById('oCorrectAnswer4').innerHTML = "Please select your answers.";
}
}
if (document.getElementById('q41').checked && document.getElementById('q43').checked) {
document.getElementById('oCorrectAnswer4').innerHTML = "Correct: The answer is " + "<u>A) Keyboard and C) Finger Print Scanner</ul>";
inputs = document.getElementsByName('q4');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox') {
inputs[i].disabled = true;
}//end of if
}//end of for
} else {
document.getElementById('oCorrectAnswer4').innerHTML = "Incorrect: The answer is " + "<u>A) Keyboard and C) Finger Print Scanner</ul>";
inputs = document.getElementsByName('q4');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox') {
inputs[i].disabled = true;
}//end of if
}//end of for
}
}//end of q4
I know this does not work, as the for loop is bypassed (I guess), but I had to start somewhere.
Any help will be appreciated.

How should I improve my javascript form validation?

I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)

How to show a required message next to input with Javascript? [duplicate]

This question already has an answer here:
This doesn't seem right? Javascript isn't working
(1 answer)
Closed 8 years ago.
I'm trying to make fields required but I want the error to show up next to the field it self not be alert?
You can put validation messages near inputs you wanna validate like
<span class="reqMsg">* First name is required</span>
Of course you need to hide them at first with css
.reqMsg {
color:red;
display:none;
}
Then in your form submit function you can change your relevant code to this
var valid = true;
var firstFocus = null;
for (var i = 0; i < rules.length; i++) {
if (!rules[i][1]) {
valid = false;
var parent = elem(rules[i][0]).parentNode;
parent.children[2].style.display = "inline";
if (firstFocus == null) firstFocus = parent.children[1];
}
}
if (!valid) {
firstFocus.focus();
return false;
}
return true;
You can see that it's not returning false immediately if one field is not valid. It checks all the fields then set a focus to first element of those that are not valid.
FIDDLE
Add span tag next to input tag
<span id="first-name-err"></span>
and change you javascript code as below
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}
var flag = true;
for (var i = 0; i < rules.length; i++) {
alert(rules[i][0]);
if (!rules[i][1]) {
var parent = elem(rules[i][0]).parentNode,
message = 'Please check your ' + (parent.textContent || parent.innerText).replace(/^\s*(.*?)\s*$/, '$1').slice(0, -1).toLowerCase() + '.';
var id = rules[i][0]+'-err';
document.getElementById(rules[i][0]+'-err').innerHTML = message;
flag = false;
}
}
return flag;
};
check this

javascript check a box with value

I am trying to check boxes in JS. I wan't to only check when the value is equal to 0, if not don't check it. my code :
document.onreadystatechange = function check(e)
{
if (document.readyState === 'complete')
{
var inputElements = document.getElementsByTagName("input");
for(var i=0; i < inputElements.length; ++i)
{
if(document.getElementsByTagName("input")[i].value == "1")
{
document.getElementById("date").checked = false;
}
}
}
}
But it doesn't work. Can you help me?
thanks
What you are doing is, if the checkboxes have value of 1, then you are checking it. Make this change in the code and it should work. Also, you need to check if you are doing this on a checkbox and not on a radio or text:
if(document.getElementsByTagName("input")[i].value == 0 &&
document.getElementsByTagName("input")[i].getAttribute("type") == "checkbox")
{
document.getElementById("date").checked = true;
}
var eles = document.querySelectorAll("input[type='checkbox']");
var len = eles.length,
i = 0,
flag = true;
for (; i < len; i++) {
if (eles[i].value === "1") {
flag = false;
return;
}
}
if (flag) document.getElementById('date').checked = true;
If the value ( 0 or 1 ) is of an <input type='text'>, then change document.querySelectorAll("input[type='checkbox']"); to document.querySelectorAll("input[type='text']");

How do I create a "check all" link for a web form?

I've got a form with a bunch of checkboxes on it, and I'd like to provide a "check all" link/button.
I'm using the code below, but when it runs, it picks up some radio buttons on the page, and checks/unchecks those too. How do I fix this?
var check = 0;
function doNow()
{
void(d=document);
void(el=d.getElementsByTagName('INPUT'));
for(i=0;i<el.length;i++)
{
if(check == 0)
void(el[i].checked=1)
else
void(el[i].checked=0)
}
if(check == 0)
check = 1;
else
check = 0;
}
You're going to want to check the element's type to ensure you don't accidentally go checking the wrong kind of inputs.
Basic example:
function checkAll( toggle ) {
var inputs = document.getElementsByTagName( 'input' );
for( var i = 0; i < inputs.length; i++ ) {
if( inputs[i].type == 'checkbox' ) {
inputs[i].checked = toggle;
}
}
}
You may want to add other checks, such as only acting on check boxes in a certain logical "group", for example.
You can check the type of the input:
if(el[i].type == 'checkbox') {
el[i].checked = true;
}
You can store the current state as a property of the function as well as check the type
function checkAll() {
var all = document.getElementsByTagName('input');
for( var i = 0, l = all.length; i < l; i++ ) {
if( all[i].type == 'checkbox' ) {
all[i].checked = checkAll.checked;
}
}
checkAll.checked = !checkAll.checked;
}
checkAll.checked = true;

Categories

Resources