Validating form in JavaScript - javascript

My code is needs to validate all questions and submit only when each input has been selected. I think this is a logical issue as my code was working before hand, but I can't seem to find where I went wrong.
What is currently happening is that the user is only alerted when there has not been a selection in the first question, even if the rest of the inputs are left empty. I am really unsure why that is and have tried rewriting this several times. I've tried rewriting this a few times, but any help is really appreciated.
<li><input type="button" value="Click" onclick="calcDate()"></li>
<br/><br/>
<li><label id="web">Do you ever think about how you would design a web page?</label></li>
<li><input type="radio" value="no" name="rad1" /><span>No</span></li>
<li><input type="radio" value="yes" name="rad2" /><span>Yes</span></li>
<li><label for="prior">Which the following are your main priorities? If none, select N/A</label></li>
<li>
<select name="prior">
<option selected="" value="Default">**Please select one of the following**</option>
<option value="ux">Ease of Use</option>
<option value="inter">Graphics & Content</option>
<option value="data">The Data Collected</option>
<option value="secure">Securing the site from possible attacks</option>
<option value="pm">Overseeing the creation of software</option>
<option value="none">None</option>
</select>
</li>
<li><label id="res">Do you enjoy conducting research, asking questions, and building reports?</label></li>
<li><input type="radio" value="no" name="rad3" /><span>No</span></li>
<li><input type="radio" value="yes" name="rad4" /><span>Yes</span></li>
<li><label for="text1">Does hacking a system or stopping a system from being hacked sound interesting to you? Type Yes or No:</label></li>
<li><textarea name="text1" id="text1" maxlength="3"></textarea></li>
<li><input type="submit" value="Finished!" onsubmit="return validateForm()"></li>
<li><input type="reset" id="reset"></li>
<script>
//form validation
function validateForm() {
//creating variables
var radio1 = document.quiz.rad1;
var radio2 = document.quiz.rad2;
var valOps = document.quiz.prior;
var radio3 = document.quiz.rad3;
var radio4 = document.quiz.rad4;
var tx1 = document.quiz.text1;
//calling functions
vWebRes(radio1, radio2, radio3, radio4);
valOps(prior);
vData(radio3, radio4);
vLength(tx1);
vCheck2(Text);
if (vWebRes(radio1, radio2, radio3, radio4)) {
if (valOps(prior)) {
if (vData(radio3, radio4)) {
if (vLength(tx1)) {
if (vCheck2(tx1)) {
return false;
}
}
}
}
}
//validating radio buttons
function vWebRes(radio1, radio2) {
x = 0;
if ((radio1.checked) || (radio2.checked)) {
x++;
}
if (x == 0) {
alert('You forgot a question!')
radio1.focus();
return false;
} else {
return true;
}
}
//validating checkbox options
function valOps(prior) {
if (prior.value == "Default") {
alert('Select an option from the drop-down menu');
prior.focus();
return false;
} else {
return true;
}
}
//validation question 3
function vData(radio3, radio4) {
z = 0;
if ((radio3.checked) || (radio4.checked)) {
z++;
}
if (z == 0) {
alert('You forgot a question!')
radio3.focus();
return false;
} else {
return true;
}
}
//validating text length
function vLength(tx1) {
var txLength = tx1.value.length;
if (txLength > 3) {
alert("That is an incorrect entry, try again.");
tx1.focus();
return false;
} else {
return true;
}
}
//validating text entry
function vCheck2(tx1) {
if ((tx1 == "Yes" || tx1 == "yes") || (tx1 == "No" || tx1 == "no")) {
tx1.focus();
return true;
} else {
alert('You entered an incorrect value, try again')
tx1.focus();
return false;
}
}
}
</script>

You might want to add the input fields (the values, .val) into an array like this, and the corresponding IDs without the .val as another array:
var arrayName = [a, b, c]; //just a mock example
var arrayNameInputs = [x, y, z]; //just a mock example, these should contain inputs with .val
And then loop through the results and check for empty indexes:
if(arrayNameInputs.indexOf("") !== -1){ //checks if there are any empty fields at all
for(i=0; i < arrayName.length; i++){
if(arrayName[i].val() == ""){
//do something, red outline, alert, w/e
}
}
}
Just make sure all your default values are " ", not "Default".
This is a bit different from how you tried to do it, but it worked for me so you might want to take a look.

I think you need to group your radio input into question.
Just rename your radio input.
See also : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
Edited: New working code. I write the comment in the code, read and try run the code.
Code:
//form validation
function validateForm() {
// you can use form
// see here: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
var quiz = document.forms[0];
// get those input
var radio1 = quiz.elements['radio1'];
var radio2 = quiz.elements['radio2'];
var selectedPrior = quiz.elements['prior'];
var textArea1 = quiz.elements['textArea1'];
// and get your answer
var formData = {
radio1: radio1.value,
selectedPrior: selectedPrior.value,
radio2: radio2.value,
textArea1: textArea1.value,
}
// you can see your answer in console [f12] developer mode
console.log("Data", formData);
// do your validation
//suggest not to nest your if clause because it will hard to read
// do it one by one and by your questions order
//if radio1 is blank
if (formData.radio1 == "") {
alert('You forgot a question!')
// in order to focus on radio input , you must specific which one you need to focus
// so I give each of them unique id
// choose one to focus
document.getElementById("radio1Yes").focus();
// document.getElementById("radio1No").focus();
// just for information, radio input focus is not visible
// if you want to stop when this is blank you just call return, it will end the function
// so the other validation will carry on when the radio1 is filled up
return;
}
//if selectedPrior is blank
if (formData.selectedPrior == "") {
alert('You forgot a question!')
selectedPrior.focus();
return;
}
//if radio2 is blank
if (formData.radio2 == "") {
alert('You forgot a question!')
document.getElementById("radio2No").focus();
return;
}
//if textArea1 is blank
if (formData.textArea1 == "") {
alert('You forgot a question!')
textArea1.focus();
return;
}
// after all value validate then you can go on submit the form
quiz.submit();
}
<!-- give your question into a form and give it a name -->
<form name="quiz">
<ol>
<li><input type="button" value="Click" onclick="calcDate()"></li>
<!-- You [must] group your radio input in order to get the value correctly-->
<li>
<label id="web">Do you ever think about how you would design a web page?
<div>
<input type="radio" id="radio1No" value="no" name="radio1" /><span>No</span>
</div>
<div>
<input type="radio" id="radio1Yes" value="yes" name="radio1" /><span>Yes</span>
</div>
</label>
</li>
<li>
<label for="prior">Which the following are your main priorities? If none, select N/A</label>
<div>
<select name="prior">
<!-- give the place holder option empty value [ just like this -> value="" ] -->
<option value="">**Please select one of the following**</option>
<option value="ux">Ease of Use</option>
<option value="inter">Graphics & Content</option>
<option value="data">The Data Collected</option>
<option value="secure">Securing the site from possible attacks</option>
<option value="pm">Overseeing the creation of software</option>
<option value="none">None</option>
</select>
</div>
</li>
<li>
<!-- remember to group your radio input -->
<label id="res">Do you enjoy conducting research, asking questions, and building reports?</label>
<div>
<input type="radio" value="no" id="radio2No" name="radio2" /><span>No</span>
</div>
<div>
<input type="radio" value="yes" id="radio2Yes" name="radio2" /><span>Yes</span>
</div>
</li>
<li>
<!-- just for suggestion: you still can use radio input on this -->
<label for="textArea1">Does hacking a system or stopping a system from being hacked sound interesting to you?
Type Yes or No:</label>
<div>
<textarea name="textArea1" id="textArea1" maxlength="3"></textarea>
</div>
</li>
<li>
<!-- I suggest to use onclick and do submition of form in javascript -->
<input type="button" value="Finished!" onclick="validateForm()">
<!-- you need to put this reset into a form to get it function correctly -->
<input type="reset" id="reset">
</li>
</ol>
</form>

Related

Requiring radio button selection in Javascript

I'm a total beginner to JS, trying to create a radio button with two options (left/right), in which one of the two options needs to be selected for the program to continue, or else it will display an error screen.
I've got code that will either prevent the participant from continuing no matter what they press (i.e. the error pops up regardless), or code that will allow the participant to continue no matter what (i.e. the program continues even if they don't select one of the options.) I feel like this could be something with my logical operators, but I'm really not sure. I've tried using a manual XOR and that doesn't seem to be the problem.
I'm using adapted code, so please let me know if there's anything else I can/should include!
<div class="radio"><label><input id="option1" name="option1" type="radio" value="Right" />Right</label></div>
<div class="radio"><label><input id="option1" name="option1" type="radio" value = "Left" />Left</label></div>
Code that causes the error no matter what:
<input onclick="function filledOut(id) { return (document.getElementById(id).value == 'Left')} if(filledOut('option1') ) { next(); }else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
Code that causes the program to continue:
<input onclick="function filledOut(id) { return ((document.getElementById(id).value == 'Left')|| (document.getElementById(id).value == 'Right'))} if(filledOut('option1') ) { next(); } else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
<form name="formName">
<input type="radio" name="option1" id="option1" value="Right"/>Right
<input type="radio" name="option2" id="option2" value="Left"/>Left
</form>
<input onclick="checkResponse()" type="button" value="Continue" />
checkResponse function will check if any options are selcted when user clicks on the continue button.
<script type="text/javascript">
function checkResponse(){
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
}
function isChecked(id){
return document.getElementById(id).checked; //returns true if any options are selected
}
</script>
You need to change the ID's to something different. In the case of radio buttons, the "name" is the radio button group. You don't need the ID's unless you are going individually look at each item, and if you give them ID's, they need to be distinct from every other ID, as well as the "name" attributes.
https://www.w3schools.com/tags/att_input_type_radio.asp
<input id="optionRight" name="groupName" type="radio" value="Right" />
<input id="optionLeft" name="groupName" type="radio" value="Left" />
Also, you can make one of the radio buttons as selected by default.
How to select a radio button by default?
<input id="option1" name="groupName" type="radio" value="Right" checked="checked" />
What I've understood is that you need to show an error if nothing is checked and continue if one of them is checked.
To do that, you will need to check if either of them is checked not checking it's value & give each radio button a unique id.
You can do something similar to this
function isChecked(id){//Instead of filledOut
return document.getElementById(id).checked;
//.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
Another function to get the value if you need it:
function getCheckedBtnValue(){
if(isChecked('option1')) return document.getElementById('option1').value
if(isChecked('option2')) return document.getElementById('option2').value
return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
next();
}else{
alert("Your error message");
}
Also, try not to write JavaScript inside of HTML elements it can be hard to read often.
Keep JavaScripting.

How do I change paragraph text using JavaScript, depending on which radio button is checked in a form?

What I´m trying to achieve is to have 1 question with 4 possible answers to choose from (radio buttons). When the user presses the button after the form, I want a paragraph to tell them more about the choice they made.
I´ve targeted the button, the paragraph and the radio buttons in my JavaScript. I´ve also managed to make the paragraph text appear whenever I choose the first radio button. However, I only want the text in the paragraph to appear if both one radio button has been chosen AND the button has been pressed. I want different content to appear in the paragraph depending on which radio button has been chosen.
Any tips or solutions would be greatly appreciated =)
Here is my code so far:
<form action="">
<h1>A friend invites you to a party. You...</h1>
<br />
<input id="red" type="radio" name="color" value="red">...bluntly tell your friend you have other priorities. <br/>
<input id="blue" type="radio" name="color" value="blue">...tell your friend you are finishing a coding assignment tonight. <br/>
<input id="yellow" type="radio" name="color" value="yellow">...hug your friend and start discussing the outfit. <br/>
<input id="green" type="radio" name="color" value="green">...thank your friend for inviting you, and tell her you look forward to it. <br/>
</form>
<button> Click me </button>
<p></p>
<script>
let btn = document.querySelector('button');
let para = document.querySelector('p');
let response = document.querySelector('input');
response.addEventListener('change', myColor);
function myColor() {
let choice = response.value;
if (choice === 'red') {
para.textContent = 'You´re so red!';
} else if (choice === 'blue') {
para.textContent = 'You´re so blue!';
} else if (choice === 'yellow') {
para.textContent = 'You´re so yellow!';
} else if (choice === 'green') {
para.textContent = 'You´re so green!';
}
}
</script>
If I understand you correctly, you can use the form you wrapped to get the selected radio value and check against it.
Like this:
<form action="">
<h1>A friend invites you to a party. You...</h1>
<br />
<input id="red" type="radio" name="color" value="red">...bluntly tell your friend you have other priorities. <br/>
<input id="blue" type="radio" name="color" value="blue">...tell your friend you are finishing a coding assignment tonight. <br/>
<input id="yellow" type="radio" name="color" value="yellow">...hug your friend and start discussing the outfit. <br/>
<input id="green" type="radio" name="color" value="green">...thank your friend for inviting you, and tell her you look forward to it. <br/>
</form>
<button> Click me </button>
<p></p>
<script>
const form = document.querySelector('form');
let btn = document.querySelector('button');
let para = document.querySelector('p');
let response = document.querySelector('input');
//response.addEventListener('change', myColor);
btn.addEventListener('click', myColor);
function myColor() {
let choice = form.color.value;
if (!choice) {
return;
}
if (choice === 'red') {
para.textContent = 'You´re so red!';
} else if (choice === 'blue') {
para.textContent = 'You´re so blue!';
} else if (choice === 'yellow') {
para.textContent = 'You´re so yellow!';
} else if (choice === 'green') {
para.textContent = 'You´re so green!';
}
}
</script>
1) When you define let response = document.querySelector('input');, you need to realize that document.querySelector only gives you one matching HTML element. This explains why only your first radio button does anything.
2) If you want anything to happen when you click the button, just add an onclick-handle to the button (button.addEventListener('click', myColor);).
3) to find the selected value in a set of radio buttons, you need to take a small detour - try like this (see also here):
let choice = document.querySelector('input[name=color]:checked');
choice = choice && choice.value;
The first line finds the selected radio button of name color. Be aware: this will be null if no radio has been selected. The second line replaces the variable's value by the radios value, if it was not null. Otherwise, it will still be null, so you can check for } else if (choice === null) { and set some text asking the user to select a color before pressing the button.
I hope this was clear enough and helps you out!
Regards,
Simon

Javascript one function validate same form checkbox group and radio button group

I'm Javascript beginner, writing JS function to validate a radio button group and a checkbox group; if either of them are completely unchecked, respective alert(s) show and stop the form submitting.
I copied code for radio button group validation, then adjusted it by adding a 2nd 'splitter' function which takes radio and checkbox names as 2 arguments, then sends both names in sequence to the 'validate' function.
This works, but is there more compact way to do this in one function, JS version of select case or something?
<script>
function splitter(mainst, Cst) {
validate(mainst);
validate(Cst);
}
//'unchecked' counts number of unchecked boxes or buttons
//then compares this to total number in the group, and if same
//this means nothing is checked, therefore show alert and return false.
function validate(grpname) {
var unchecked = 0, selectgroup=document.getElementsByName(grpname)
for(i=0;i<selectgroup.length;i++) {
if(selectgroup.item(i).checked == false) {
unchecked++;
}
}
if(unchecked == selectgroup.length) {
if (grpname == 'mainstreet') {
alert("Please select a main street");
return false;
}
else {
alert("Please select your C street(s)");
return false;
}
} else {
return true;
}
}
</script>
Example form here:
<form action="" method="post" onsubmit="return splitter('mainstreet', 'Cstreet')">
Street:
<input type="radio" name="mainstreet" value="jones"> jones street
<input type="radio" name="mainstreet" value="bones"> bones street
<input type="radio" name="mainstreet" value="drones"> drones street
<input type="radio" name="mainstreet" value="foobar"> foobar street
<br /><br />
Side street:
<input type="checkbox" name="Cstreet" value="barfoo"> barfoo street
<input type="checkbox" name="Cstreet" value="candoo"> candoo street
<input type="checkbox" name="Cstreet" value="cantdo"> cantdo street
<input type="checkbox" name="Cstreet" value="canoe"> canoe street
<input type="checkbox" name="Cstreet" value="wahoo"> wahoo street
<input type="submit" value="Submit" />
</form>
<script>
function splitter(mainst, Cst) {
if(document.querySelector('input[name="'+mainst+'"]:checked') == null ){
alert("Please select a main street");
return false;
}
else if (document.querySelector('input[name="'+Cst+'"]:checked') == null) {
alert("Please select your C street(s)");
return false;
}
}
</script>

validating at least one checkbox selected on dynamically added fields

If you're dynamically adding form fields to an existing form, what's the best way of adding validation?
Consider this fiddle: http://jsfiddle.net/yWGK4/
<form action="#" method="post">
<div id="parent">
<div class="child">
<input type="checkbox" name="box1[]" value="1" /> 1
<input type="checkbox" name="box1[]" value="2" /> 2
<input type="checkbox" name="box1[]" value="3" /> 3
</div>
</div>
</form>
<button id="addBoxes">Add Boxes</button>
<script>
$(function() {
var parentdiv = $('#parent');
var m = $('#parent div.child').size() + 1;
$('#addBoxes').on('click', function() {
$('<div class="child"><input type="checkbox" name="box'+m+'[]" value="1" /> 1 <input type="checkbox" name="box'+m+'[]" value="2" /> 2 <input type="checkbox" name="box'+m+'[]" value="3" /> 3 </div>').appendTo(parentdiv);
m++;
return false;
});
});
</script>
On that form I'm adding new checkbox groups, and want to make sure at least one box from each group is checked (not one box across all groups). Anyone got any clever methods? Everything I've looked at would get very complicated due to the dynamically added fields.
It doesn't matter if the checkboxes are dynamic when validating on submit etc. so something like this would check if at least one checkbox per .child is checked :
$('form').on('submit', function(e) {
e.preventDefault();
var valid = true;
$('.child').each(function() {
if ( ! $('[type="checkbox"]:checked', this).length ) // no box checked
valid = false;
});
if (valid) {
this.submit();
}else{
alert('error');
}
});
FIDDLE
If you want to check it using jQuery you can use `.each()
$(".child").each(function(){
var $this = $(this);
var checked = $this.find("input:checked");
if( checked.lenght == 0 ) {
alert("This group is not valid");
}
});
You can find more about this jQuery functions in this links:
each()
find()
here's what I came up with. Basically you loop over the .child groups and test if they have a checkbox in the checked state..
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});

Check to see if none of the checkboxes was checked in jquery

I have two checkboxes and one of the checkboxes must be checked. I can see that it's right, no syntax errors. What should be made to my code to check if none of the checkboxes were checked?
HTML :
<input type="checkbox" value="aa" class="first" name="a"> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b"> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
JavaScript:
$('button').on('click',function(){
if( $(".first:not(:checked)") && $(".second:not(:checked)") ){
$('.error').text('You must select atleast one!');
}else
$('.error').hide();
});
Example : http://jsfiddle.net/ptbTq/
Check this fiddle: http://jsfiddle.net/692Dx/
Checking code:
if($('input[type="checkbox"]:checked').length == 0) {
alert('none checked');
}
You are using selectors which do not return boolean values which is what you need when writing an if condition. Here's what you could do:
$('button').on('click',function() {
if(!$(".first").is(":checked") && !$(".second").is(":checked")) {
$('.error').text('You must select atleast one!').show();
} else {
$('.error').hide();
}
});
or if you prefer and think it could be more readable you could invert the condiciton:
$('button').on('click',function() {
if($(".first").is(":checked") || $(".second").is(":checked")) {
$('.error').hide();
} else {
$('.error').text('You must select atleast one!').show();
}
});
Also notice that you need to .show() the error message in the first case as you are hiding it in the second.
And here's a live demo.
Short:
$("input[type=checkbox]").is(":checked")
returns true if:
one of your checkboxes - from the selector ("input[type=checkbox]") - is checked.
else return false
and in your case:
$(".first, .second").is(":checked")
Do something at least one of your checkboxes is checked
Put the same class on both checkboxes and you can do something like
if ($(':checkbox.the_class:checked').length > 0) {
// at least one checkbox is checked
// ...
}
The best would be to put your checkboxes inside a div with an unique ID so you can verify all the checkboxes in there, so your code will work in all cases. Even when adding new checkboxes to the div later on.
<div id="cb">
<input type="checkbox" value="aa" class="first" name="a" /> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b" /> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
</div>
Your JQuery:
$('button').click(function() {
var checked_one = $('div#cb input[type="checkbox"]').is(':checked');
if (!checked_one )
$('.error').text('You must select atleast one!');
else
$('.error').hide();
});
Live demo can be seen here: http://jsfiddle.net/ptbTq/15/

Categories

Resources