I have a series of randomly generated textbox and radio-button inputs. It's kinda like a Quiz, so what I would like to do is collect all of the inputs and send them to the server so it can evaluate them.
Now, to make it easier, I put all of the radio-button inputs to the end.
I use the following code to collect the inputs of the textbox-types:
$('#button_submit').click(function() {
var answer_list = '';
$('input:text').each(function(index,data) {
answer_list = answer_list + '$' + $(data).val();
}
...
}
This works perfectly, but after this, I don't know what to do. I could loop through the input:radio:checked elements and add the value of those to my string, which would work perfectly, except if the user decides to submit their answers while leaving one of the radio-button inputs empty. In that case, nothing gets added to the string and the server will be missing the answer to that question and it messes everything up.
So I need to add something to my string when the code realizes that there is a radio-button question, but no answer was chosen, but I have no idea how to do it.
Edit:
HTML example:
<div class="form-group" id="form-group-34">
<label class="control-label " for="question">What is 92848 × 71549?</label>
<input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
<label class="control-label " for="question">Is 194 divisible by 3?</label>
<br><input id="14-answer-0" name="14-answer" type="radio" value="1">
<label for="14-answer-0">Yes</label>
<br><input id="14-answer-1" name="14-answer" type="radio" value="0">
<label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
<label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
<br><input id="35-answer-0" name="35-answer" type="radio" value="1">
<label for="35-answer-0">Monday</label>
<br><input id="35-answer-1" name="35-answer" type="radio" value="2">
<label for="35-answer-1">Tuesday</label>
<br><input id="35-answer-2" name="35-answer" type="radio" value="3">
<label for="35-answer-2">Wednesday</label>
<br><input id="35-answer-3" name="35-answer" type="radio" value="4">
<label for="35-answer-3">Thursday</label>
<br><input id="35-answer-4" name="35-answer" type="radio" value="5">
<label for="35-answer-4">Friday</label>
<br><input id="35-answer-5" name="35-answer" type="radio" value="6">
<label for="35-answer-5">Saturday</label>
<br><input id="35-answer-6" name="35-answer" type="radio" value="0">
<label for="35-answer-6">Sunday</label>
</div>
But the problem is, that these questions are randomly generated. So there can be 5 simple textbox-type inputs, then 5 radio-button type ones, or there might be only 1 radio-button type question, and all of their attributes are generated dynamically, so I can't really put the radio-button group's name in the code, because I don't know it.
You could use this to see if they are all checked:
var allRadios = $('input[name="namevalue"][type=radio]').length;
var allCheckedRadios $('input[name="namevalue"][type=radio]').filter(function() {
return this.checked;
}).length;
if( allRadios == allCheckedRadios){
// do what you need
}
whatever your name is change "namevalue" to that. The same basic logic to get the values can be applied.
Note: performance gain for modern browsers on these selector forms above over $('input:radio') can be had.
EDIT From updated question:
Here I applied the techniques above to walk through each of the form groups looking for radio buttons, and if they exist throw an alert if none are checked within that group. You could also create and return a Boolean value if ANY of the groups have radio selections with none selected. "hasUncheckedRadios" will be either 0 if none are checked or 1 if one is checked - since radio buttons within a group only select one. You could use this logic in your validation to ensure that all of the groups have a valid checked radio button (IF they contain a radio that is);
function checkRadios() {
var allGroups = $('.form-group');
allGroups.each(function() {
var allRadios = $(this).find('input[type=radio]').length;
var hasUncheckedRadios = $(this).find('input[type=radio]').filter(function() {
return this.checked;
}).length;
console.log('total:' + allRadios + ' checked:' + hasUncheckedRadios);
// if allRadios is > 0 then radios exist and hasUncheckedRadios == 0 none are checked
if (allRadios && !hasUncheckedRadios) {
alert("Form Group" + $(this).attr('id') + " has radio buttons unaswered");
}
});
}
$('#checkem').on('click', function() {
console.log('checking...');
checkRadios();
});
fiddle with it here: https://jsfiddle.net/MarkSchultheiss/nv7cjpr2/
I would iterate a bit more: https://jsfiddle.net/Twisty/ghc7u2ab/
HTML
<div class="form-group" id="form-group-34">
<label class="control-label " for="question">What is 92848 × 71549?</label>
<input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
<label class="control-label " for="question">Is 194 divisible by 3?</label>
<br>
<input id="14-answer-0" name="14-answer" type="radio" value="1">
<label for="14-answer-0">Yes</label>
<br>
<input id="14-answer-1" name="14-answer" type="radio" value="0">
<label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
<label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
<br>
<input id="35-answer-0" name="35-answer" type="radio" value="1">
<label for="35-answer-0">Monday</label>
<br>
<input id="35-answer-1" name="35-answer" type="radio" value="2">
<label for="35-answer-1">Tuesday</label>
<br>
<input id="35-answer-2" name="35-answer" type="radio" value="3">
<label for="35-answer-2">Wednesday</label>
<br>
<input id="35-answer-3" name="35-answer" type="radio" value="4">
<label for="35-answer-3">Thursday</label>
<br>
<input id="35-answer-4" name="35-answer" type="radio" value="5">
<label for="35-answer-4">Friday</label>
<br>
<input id="35-answer-5" name="35-answer" type="radio" value="6">
<label for="35-answer-5">Saturday</label>
<br>
<input id="35-answer-6" name="35-answer" type="radio" value="0">
<label for="35-answer-6">Sunday</label>
</div>
<button id="button_submit">Submit</button>
JQuery
$("#button_submit").click(function() {
var answer_list = {};
$(".form-group").each(function(i, v) {
console.log("Index:", i, "ID: [", $(v).attr("id"), "]");
answer_list[$(v).attr("id")] = {};
var ind = $(v).find("input");
$.each(ind, function(i2, el) {
console.log("Type of Element:", $(el).attr("type"));
switch ($(el).attr("type")) {
case "text":
answer_list[$(v).attr("id")][$(el).attr("id")] = ($(el).val() != "") ? $(el).val() : null;
break;
case "radio":
var isAnswered = false;
$(el).each(function(i3, rad) {
if ($(rad).is(":checked")) {
answer_list[$(v).attr("id")][$(rad).attr("name")] = $(rad).val();
isAnswered = true;
}
if (!isAnswered) {
answer_list[$(v).attr("id")][$(el).eq(0).attr("name")] = null;
}
});
break;
}
});
});
console.log(answer_list);
return false;
});
Possible Result
answer_list: {
form-group-34: {
input34: null
},
form-group-35: {
14-answer: 0
},
form-group-36: {
35-answer: null
}
}
This will iterate each group and look for an answer. If one is found, the value is added. If not, null is added as the result.
loop class group that has radio then use .prop("checked")
var frmGroup= 0, checked= 0;
$('.form-group').each(function(index) {
if ($(this).children('input:radio').length > 0) {
frmGroup++;
$(this).children('input:radio').each(function(index) {
if ($(this).prop("checked") == true) {
checked++;
}
});
}
});
if(frmGroup != checked)...
working example: https://jsfiddle.net/nsL3drz5/
Related
In my project I want change src part (ar-button's src) related to my radio buttons check.
For ex: When you check "Option 1" I want to change src part on ar-button. Than when you check Option3x(with checked option1 and option1x) I want to change src again.
I mean for all 64 combination of checks I want to change src.
Any help or suggestion would be great!
Thanks..
<label>
<input type="radio" id="diffuse" name="kumas" value="textues/kumas/2/pgwfpjp_2K_Albedo.jpg"checked>
Option1
</label>
<label>
<input type="radio"id="adiffuse" name="kumas" value="textues/kumas/1/oi2veqp_2K_Albedo.jpg">
Option 2
</label>
<label>
<input type="radio" id="bdiffuse"name="kumas" value="textues/kumas/3/sjfvce3c_2K_Albedo.jpg">
Option 3
</label>
<label>
<input type="radio" id="cdiffuse"name="kumas" value="textues/kumas/4/sjfvcjzc_2K_Albedo.jpg">
Option 4
</label>
<br><br>
<label>
<input type="radio" id="diffuse1" name="kol" value="textues\kol\1\teqbcizc_2K_Albedo.jpg" checked>
Option 1x
</label>
<label>
<input type="radio" id="adiffuse1" name="kol" value="textues\kol\2\tfjbderc_2K_Albedo.jpg">
Option 2x
</label>
<label>
<input type="radio" id="bdiffuse1"name="kol" value="textues\kol\3\tcnodi3c_2K_Albedo.jpg">
Option 3x
</label>
<label>
<input type="radio" id="cdiffuse1"name="kol" value="textues\kol\4\tcicdebc_2K_Albedo.jpg">
Option 4x
</label>
</div>
</div>
</div>
<br><br>
<label>
<input type="radio" id="diffuse2" name="dugme" value="textues\metal\1\scksebop_2K_Albedo.jpg" checked>
Option 1z
</label>
<label>
<input type="radio" id="adiffuse2" name="dugme" value="textues\metal\2\se4objgc_2K_Albedo.jpg">
Option 2z
</label>
<label>
<input type="radio" id="bdiffuse2"name="dugme" value="textues\metal\3\se4pcbbc_2K_Albedo.jpg">
Option 3z
</label>
<label>
<input type="radio" id="cdiffuse2"name="dugme" value="textues\metal\4\shkxcgfc_2K_Albedo.jpg">
Option 4z
</label>
<br><br>
<ar-button
id="change" src="https://basebros.com/models/ar_base_tekli_koltuk_3d.glb"
id="change2 ios-src="https://basebros.com/models/ar_base_tekli_koltuk_3d.usdz"
title="3D-AR by BASE">
<img class="arbuttonicon" src="Assets/evindebutton.png" width="170px" alt="AR-icon">
</ar-button>
Try using this code:
const kumas = document.getElementsByName("kumas");
const kol = document.getElementsByName("kol");
const dugme = document.getElementsByName("dugme");
const arButton = document.querySelector("ar-button");
let sources = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]; /* Fill this with the sources. The first element is if the first option for kumas is selected, the second is for if the second option is selected, etc. The elements inside those elements are for each of the different options for kol, and the elements inside those elements are for each of the different options for dugme. */
function foo() {
let kumasSelected;
let kolSelected;
let dugmeSelected;
for(let i of kumas) {
if(i.checked) {
kumasSelected = kumas.indexOf(i);
}
}
for(let i of kol) {
if(i.checked) {
kolSelected = kol.indexOf(i);
}
}
for(let i of dugme) {
if(i.checked) {
dugmeSelected = dugme.indexOf(i);
}
}
arButton.src = sources[kumasSelected][kolSelected][dugmeSelected];
}
Run the function each time you want to update the source.
<label>
<input type="radio" id="diffuse" name="kumas" value="textues/kumas/2/pgwfpjp_2K_Albedo.jpg"checked>
Option1
</label>
<label>
<input type="radio"id="adiffuse" name="kumas" value="textues/kumas/1/oi2veqp_2K_Albedo.jpg">
Option 2
</label>
<label>
<input type="radio" id="bdiffuse"name="kumas" value="textues/kumas/3/sjfvce3c_2K_Albedo.jpg">
Option 3
</label>
<label>
<input type="radio" id="cdiffuse"name="kumas" value="textues/kumas/4/sjfvcjzc_2K_Albedo.jpg">
Option 4
</label>
<br><br>
<label>
<input type="radio" id="diffuse1" name="kol" value="textues\kol\1\teqbcizc_2K_Albedo.jpg" checked>
Option 1x
</label>
<label>
<input type="radio" id="adiffuse1" name="kol" value="textues\kol\2\tfjbderc_2K_Albedo.jpg">
Option 2x
</label>
<label>
<input type="radio" id="bdiffuse1"name="kol" value="textues\kol\3\tcnodi3c_2K_Albedo.jpg">
Option 3x
</label>
<label>
<input type="radio" id="cdiffuse1"name="kol" value="textues\kol\4\tcicdebc_2K_Albedo.jpg">
Option 4x
</label>
</div>
</div>
</div>
<br><br>
<label>
<input type="radio" id="diffuse2" name="dugme" value="textues\metal\1\scksebop_2K_Albedo.jpg" checked>
Option 1z
</label>
<label>
<input type="radio" id="adiffuse2" name="dugme" value="textues\metal\2\se4objgc_2K_Albedo.jpg">
Option 2z
</label>
<label>
<input type="radio" id="bdiffuse2"name="dugme" value="textues\metal\3\se4pcbbc_2K_Albedo.jpg">
Option 3z
</label>
<label>
<input type="radio" id="cdiffuse2"name="dugme" value="textues\metal\4\shkxcgfc_2K_Albedo.jpg">
Option 4z
</label>
<br><br>
<ar-button
src="https://basebros.com/models/ar_base_tekli_koltuk_3d.glb"
title="3D-AR by BASE">
<img class="arbuttonicon" src="Assets/evindebutton.png" width="170px" alt="AR-icon">
</ar-button>
<script>
const kumas = document.getElementsByName("kumas");
const kol = document.getElementsByName("kol");
const dugme = document.getElementsByName("dugme");
const arButton = document.querySelector("ar-button");
let sources = [[["https://basebros.com/models/ar_base_ayakkabi.glb"],["https://basebros.com/models/ar_base_camasir_makinesi_3d.glb"],["https://basebros.com/models/ar_base_kahve_makinesi_3d.glb"],["https://basebros.com/models/ar_base_nintendo.glb"]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]; /* Fill this with the sources. The first element is if the first option for kumas is selected, the second is for if the second option is selected, etc. The elements inside those elements are for each of the different options for kol, and the elements inside those elements are for each of the different options for dugme. */
function foo() {
let kumasSelected;
let kolSelected;
let dugmeSelected;
for(let i of kumas) {
if(i.checked) {
kumasSelected = kumas.indexOf(i);
}
}
for(let i of kol) {
if(i.checked) {
kolSelected = kol.indexOf(i);
}
}
for(let i of dugme) {
if(i.checked) {
dugmeSelected = dugme.indexOf(i);
}
}
arButton.src = sources[kumasSelected][kolSelected][dugmeSelected];
}
</script>
I know this has been already asked. I checked all the previous question about this topic but I can't find a solution.
This is the problem: I have two input, one is a checkbox and the other one is a radio with three possible choices. Inside a function I have to see firstly if the first checkbox is checked, if yes I will check some other things with an if else statement, otherwise the function will proceed. The radio input will appear later inside the same function. This one will check which of the three choices had been checked previously and will set a variable equal to the value of the checked one. To see if the checkbox is checked I use jQuery with .is(':checked'), but it every returns false, even if I checked them. Any idea?
Sorry if I haven't properly used Stack Overflow, but this is my first question.
This is the HTML, the input is #geoloc_waypoint_active and the radio is #locomotion_radio
<div id="create_route_modal_content" class="modal-body">
<div id="geo_switch">
<div id="geoSwitchDiv">
<label for="geoloc_waypoint_active">
Usa la tua posizione
</label>
<label class="switch">
<input id="geoloc_waypoint_active" class="form-check form-check-inline" type="checkbox">
<span class="slider round"></span>
</label>
</div>
<br>
<div id="locomotion_radio">
<label><input class="locomInput" type="radio" name="locomotion" value="walking" checked><img class='locomotionImg' src='immagini/walking.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="cycling"><img class='locomotionImg' src='immagini/cycling.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="driving"><img class='locomotionImg' src='immagini/driving.png'></label>
</div>
DrawOnMap() {
let formattedCoord = "";
let geoposition = $('#geoloc_waypoint_active').is(':checked');
console.log(geoposition)
if (geoposition) {
var geoL = $('#geo_Locator .mapboxgl-ctrl .mapboxgl-ctrl-icon');
if (!map.getLayer('points') && geoL.attr('aria-pressed') === 'false') {
alert("L'utente non ha una posizione attualmente attiva.");
return;
} else {
this.waypoints.unshift(window.userPosition);
}
}
if (this.waypoints.length < 2) {
alert("Devi inserire almeno due punti di interesse.");
return;
}
this.waypoints.forEach((waypoint, index, source) => {
formattedCoord += waypoint[0] + "," + waypoint[1];
if (index < source.length - 1) {
formattedCoord += ";";
}
});
let locomotion = $('input[name=locomotion]:checked').val();
let geoposition = $('#geoloc_waypoint_active').is(':checked'); is always false and so It never enter the if
Same thing with let locomotion = $('input[name=locomotion]:checked').val(); It can't find the checked one and set locomotion
have you tried this $("#geoloc_waypoint_active")[0].checked it will give you control right value.
$(document).ready(function(){
console.log($("#geoloc_waypoint_active")[0].checked)
$('#check').on('click',function(){
console.log($("#geoloc_waypoint_active")[0].checked)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value='checkVakue' type='button' id='check'/>
<div id="create_route_modal_content" class="modal-body">
<div id="geo_switch">
<div id="geoSwitchDiv">
<label for="geoloc_waypoint_active">
Usa la tua posizione
</label>
<label class="switch">
<input id="geoloc_waypoint_active" class="form-check form-check-inline" type="checkbox">
<span class="slider round"></span>
</label>
</div>
<br>
<div id="locomotion_radio">
<label><input class="locomInput" type="radio" name="locomotion" value="walking" checked><img class='locomotionImg' src='immagini/walking.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="cycling"><img class='locomotionImg' src='immagini/cycling.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="driving"><img class='locomotionImg' src='immagini/driving.png'></label>
</div>
I am working on a five star rating system. There are five star icons. When an icon is clicked, I want to change the value of an input to whichever star is clicked(e.g. if the fourth star is clicked, the input will have a value of 4). My problem is that the click method that I apply to the newly created icon does not work at all. What am I doing wrong? Here is a jsFiddle to demonstrate.
html
<div class="rating" style="float: none;clear: both;">
<noscript>
<label class="radio-inline">
<input type="radio" name="stars" value="1" title="1 Star"> 1
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="2" title="2 Stars"> 2
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="3" title="3 Stars"> 3
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="4" title="4 Stars"> 4
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="5" title="5 Stars"> 5
</label>
</noscript>
</div>
<input type="text" name="stars" value="" id="stars">
Javascript
$element = $('.rating');
$element.empty();
for (var i = 0; i < 5; i++) {
var occurrence = i + 1;
var newStar = $('<i class="fa fa-star-o" title="' + occurrence + ' stars" data-occurrence="' + occurrence + '"></i>');
newStar.on('click', function() {
$('#stars').val(occurrence + ' stars given.');
});
$element.append(newStar);
}
$element.each(function() {
var _parent = $(this);
var originalStars = _parent.html();
$(_parent).on('mouseover', 'i[class*="fa-star"]', function() {
var starOccurrence = $(this).prevAll().andSelf().length;
$(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
}).mouseout(function() {
$(_parent).html(originalStars);
});
});
2 problems.
Mentioned in the comments, don't replace the inner html, just remove/add classes to reset the stars.
.mouseout(function() {
$('i').removeClass('fa-star').addClass('fa-star-o');
});
Second problem is you need to grab the occurrence value from the data attribute, and not the overwritten occurrence variable.
$('#stars').val($(this).data('occurrence') + ' stars given.');
jsFiddle: https://jsfiddle.net/9mLzLsw7/2/
I am trying to show a red circle with the "!" when the radio buttons are unchecked and to show a green circle when both are checked. After that I use a function to make the button submit or not according to the red/green circle.
I've tried many ways to tangle with the code but it doesn't want to show the green circle when it's checked any idea why ?
PS:
span3 (red circle )
span2 (green circle)
Basically I want to make my form validation by js not by php ...
HTML:
<label id="labelage">Age:</label>
<br>
<input type="radio" id="under_13" value="under_13" name="age">
<label for="under_13" class="light">Under 13</label>
<input type="radio" id="over_13" value="over_13" name="age">
<label for="over_13" class="light">13 or Older</label>
<div class="break"></div>
<div id="borderlabel">
<label id="labelage1">Gender:</label>
<input type="radio" id="male" value="male" name="gender">
<label for="male" class="light1">Male</label>
<input type="radio" id="female" value="female" name="gender">
<label for="female" class="light1">Female</label>
</div>
....
<button type="submit" id="signupb" name="register">Sign up
<div class="span3">!</div>
<div class="span2">✔</div>
</button>
JavaScript
$(".span1").hide();
$(".span2").hide();
$(".span3").hide();
function submit() {
if (!$('#male').is(':checked') || !$('#female').is(':checked')) {
$(".span3").show();
} else {
if (!$('#under_13').is(':checked') || !$('#over_13').is(':checked')) {
$(".span3").show();
} else {
$(".span2").show();
}
}
}
$("#signupb").on("mouseover", submit);
Your logic is off
Have the radio clicks also update the !
Do not call something submit
Cancel the submission if clicking anyway
Try this:
function checkRad() {
var ok = ($('#male').is(':checked') || $('#female').is(':checked')) &&
($('#under_13').is(':checked') || $('#over_13').is(':checked'))
$(".span3").toggle(!ok);
$(".span2").toggle(ok);
return ok;
}
$(function() {
$(".span1").hide();
$(".span2").hide();
$(".span3").hide();
$("#signupb").on("mouseover", checkRad)
.on("click", function(e) {
if (!checkRad()) e.preventDefault();
})
$("input[type=radio]").on("click", function() {
checkRad();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label id="labelage">Age:</label>
<br>
<input type="radio" id="under_13" value="under_13" name="age">
<label for="under_13" class="light">Under 13</label>
<input type="radio" id="over_13" value="over_13" name="age">
<label for="over_13" class="light">13 or Older</label>
<div class="break"></div>
<div id="borderlabel">
<label id="labelage1">Gender:</label>
<input type="radio" id="male" value="male" name="gender">
<label for="male" class="light1">Male</label>
<input type="radio" id="female" value="female" name="gender">
<label for="female" class="light1">Female</label>
</div>
....
<button type="submit" id="signupb" name="register">Sign up
<div class="span3">!</div>
<div class="span2">✔</div>
</button>
I would recommend using jQuery Validation plugin instead
It's bad practice to assign IDs to every input element, makes code harder to maintain. Consider accessing elements by name attribute.
Consider adding server-side validation as well against browser errors/malicious users.
Change your submit() function to:
function validateForm() {
$(".span2").hide();
$(".span3").hide();
var isError = false;
if (!$('#male').is(':checked') && !$('#female').is(':checked')) {
isError = true
} else if (!$('#under_13').is(':checked') && !$('#over_13').is(':checked')) {
isError = true;
}
if(isError){
$(".span3").show();
} else {
$(".span2").show();
}
}
$("#signupb").on("mouseover", validateForm);
DEMO
I'm trying to validate the radio button group,. if not check the span will have a text which indicates that the radio button must be selected,. the problem is,. if I place the codes of radion button validation on top, it does not work, but when it is below,. it works.. Kinda weird,. any idea for this one? thanks
$("#mchoice").submit(function () {
var direction = $('#direction').val();
var quiztxtBox = document.getElementsByName('quiztxtBox[]');
var isSubmit;
var names = [];
var err = document.getElementsByName('errMchoice[]');
// For radio button answers.
$('input[type="radio"]').each(function(){
names[$(this).attr('name')] = true;
});
if (!direction)
{
$('#direction').focus();
$('#direction').css({"background-color":"#f6d9d4"});
$('#direction').nextAll('span').html('Type in direction.');
event.preventDefault();
}
else
{
$('#direction').css({"background-color":"#fff"});
$('#direction').nextAll('span').html("");
}
for(correct_answer in names)
{
var radio_buttons = $("input[name='" + correct_answer + "']");
if( radio_buttons.filter(':checked').length == 0)
{
radio_buttons.nextAll('span').html('Select the answer.');
event.preventDefault();
}
else
{
radio_buttons.nextAll('span').html('');
}
}
// Choices fields
$("[name='quiztxtBox[]']").each(function(){
if (!this.value.length)
{
$(this).css({"background-color":"#f6d9d4"}).siblings('span.errorMsg').text('Please type in question/answer!');
event.preventDefault();
}
else
{
$(this).css({"background-color":"#fff"}).siblings('span.errorMsg').text("");
}
});
});
HTML here
<div id="QuestionTBDiv1" >
<label>Question</label><br/>
<input type="text" name="quiztxtBox[]" size="57" id="quiztxtBox[]" placeholder="Question #1"><br/>
<label>Answer</label><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A"> <input type="radio" class = "choiceA" name="correct_answer1" value="A">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice B"> <input type="radio" class = "choiceB" name="correct_answer1" value="B"><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice C"> <input type="radio" class = "choiceC" name="correct_answer1" value="C">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice D"> <input type="radio" class = "choiceD" name="correct_answer1" value="D"><br>
<span name="errMchoice" class="errorMsg"></span>
</div>
JsFiddle:http://jsfiddle.net/Ej77L/2/
There was a small logical error in your javascript.
Once you set the span with error message of 'Select an answer' you are doing a checking if the question has been filled. If it has been filled then you are making the span text empty.
So instead of that, keep a flag to see if the answer was selected or not. If not selected then set the flag and in later part of the code, don't empty span text
Here's a working DEMO