Javascript conditionals not working on correct button combination - javascript

I have 5 if else conditions under function getRadioButtonValue. The function does not go through all the conditions even after clicking the right button combinations.
I have tried to debug the script using Chrome Developer tools but the problem still exists. Where is the code breaking?
Some information regarding the page, I am using Javascript to hide the div's and headers so that at any one time there is only one question seen.
Only the first if conditions work, but nothing else
The results are seen after Get Result button is clicked on the last page which should redirect to the appropriate page.
[DELETED CODE]
[UPDATED CODE]
I am unable to auto hide my div's based on the response given below by Keith.
FYI: His code works as expected.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.hidden {
display: none;
}
.visible {
display: block;
margin: 0 auto;
width: 650px;
height: 445px;
background: #EFDFBC;
}
</style>
</head>
<body>
<div id="first-question" class="visible">
<h3>How?</h3>
<ul>
<li>abc</li>
<li>def</li>
</ul>
<hr>
<input type="radio" name="quiz-question-one" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" name="quiz-question-one" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
</div>
<div id="second-question" class="hidden">
<h3>To</h3>
<hr>
<input type="radio" name="quiz-question-two" id="quiz-question-two-yes" value="yes" />
<label for="quiz-question-two-yes" id="twoYes">Yes</label>
<input type="radio" name="quiz-question-two" id="quiz-question-two-no" value="no" />
<label for="quiz-question-two-yes" id="twoNo">No</label>
</div>
<div id="third-question" class="hidden">
<h3>Make </h3>
<hr>
<input type="radio" name="quiz-question-three" id="quiz-question-three-yes" value="yes" />
<label for="quiz-question-three-yes" id="threeYes">Yes</label>
<input type="radio" name="quiz-question-three" id="quiz-question-three-no" value="no" />
<label for="quiz-question-three-yes" id="threeNo">No</label>
</div>
<div id="fourth-question" class="hidden">
<h3>This</h3>
<hr>
<input type="radio" name="quiz-question-four" id="quiz-question-four-yes" value="yes" />
<label for="quiz-question-four-yes" id="fourYes">Yes</label>
<input type="radio" name="quiz-question-four" id="quiz-question-four-no" value="no" />
<label for="quiz-question-four-yes" id="fourNo">No</label>
</div>
<div id="fifth-question" class="hidden">
<h3>Work?</h3>
<hr>
<input type="radio" name="quiz-question-five-yes" id="quiz-question-five-yes" value="yes" />
<label for="quiz-question-five-yes" id="fiveYes">Yes</label>
<input type="radio" name="quiz-question-five-no" id="quiz-question-five-no" value="no" />
<label for="quiz-question-five-yes" id="fiveNo">No</label>
</div>
<div class="page result">
<label>Results</label>
<div id="result"></div>
</div>
</body>
</html>
<script type="text/javascript">
var results = {};
function updateResult() {
var r = results,
rt = $('#result');
if (r.quiz-question-one && r.quiz-question-two && r.quiz-question-three && r.quiz-question-four && r.quiz-question-five) {
rt.text('All Yes');
} else if (!r.quiz-question-one && !r.quiz-question-two && !r.quiz-question-three && !r.quiz-question-four && !r.quiz-question-five) {
rt.text('All No');
} else {
rt.text('We have a mixed response');
}
}
$(function () {
$('body').on('click', '[name]', function () {
var $this = $(this),
page = $this.closest('.hidden'),
next_page = $(page.next());
results[$this.attr('name')] = $(this).val() === 'yes';
page.removeClass('visible');
next_page.addClass('visible');
if (next_page.hasClass('result')) updateResult();
});
});
</script>

I've created an example below that I think you can work from. The values from the radio I don't think get updated until you submit, instead I've captured the results in the onclick. You can now add back you CSS styling etc. Hope that helps.
var results = {};
function updateResult() {
var r = results,
rt = $('#result');
if (r.q1 && r.q2 && r.q3) {
rt.text('All Yes');
} else if (!r.q1 && !r.q2 && !r.q3) {
rt.text('All No');
} else {
rt.text('We have a mixed response');
}
}
$(function () {
$('body').on('click', '[name]', function () {
var $this = $(this),
page = $this.closest('.page'),
next_page = $(page.next());
results[$this.attr('name')] = $(this).val() === 'yes';
page.removeClass('active');
next_page.addClass('active');
if (next_page.hasClass('result')) updateResult();
});
});
.page {
display: none;
}
.page.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page active">
<div>Question 1</div>
<label for="q1yes">Yes</label>
<input id="q1yes" type="radio" name="q1" value="yes">
<label for="q1no">No</label>
<input id="q1no" type="radio" name="q1" value="no">
</div>
<div class="page">
<div>Question 2</div>
<label for="q2yes">Yes</label>
<input id="q2yes" type="radio" name="q2" value="yes">
<label for="q2no">No</label>
<input id="q2no" type="radio" name="q2" value="no">
</div>
<div class="page">
<div>Question 3</div>
<label for="q3yes">Yes</label>
<input id="q3yes" type="radio" name="q3" value="yes">
<label for="q3no">No</label>
<input id="q3no" type="radio" name="q3" value="no">
</div>
<div class="page result">
<label>Results</label>
<div id="result"></div>
</div>
<input type="radio" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
In the above you are using type="radio", that means all type="radio" with the same name will group together, and not just these two. To group together just give them a name on the input. eg.
<input type="radio" name="quiz-question-one" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" name="quiz-question-one" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
Above you can see I've given the 2 inputs the name="quiz-question-one", and then for the next question maybe give them a name="quiz-question-two" etc..
On another note, there are lots of places where your code could be simplified, but hopefully this will solve your current problem.

Related

Radio button Show/Hide on parent element on page load

In the below code, show/hide is not happening on page reload. If I check another radio button after page reloading, it's working. Help me to resolve the same.
$(window).load(function(){
$("[name=image_type]").on("change",imageTypeToggle);
})
function imageTypeToggle(){
let selectedValue, $showElements, $hideElements;
selectedValue = $(this).val();
$hideElements = $(this).parents(".image_video_sec").find(".image_sec, .video_sec");
$hideElements.hide().find("input").attr('disabled',true);
if(selectedValue == "0") {
$showElements = $(this).parents(".image_video_sec").find(".image_sec");
} else if(selectedValue == "1") {
$showElements = $(this).parents(".image_video_sec").find(".video_sec");
}
$showElements.show().find("input").attr('disabled',false);
};
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
One way to do it is to trigger a click on the radio button when the document loads. (I changed your $(window).load (which was throwing an error) to $(document).ready.
$("[name=image_type]").eq(0).trigger('click')
$(document).ready(function() {
$("[name=image_type]").on("change", imageTypeToggle);
$(".image_video_sec").each(function() {
$(this).find("[name=image_type]").eq(0).trigger('click')
})
})
function imageTypeToggle() {
let selectedValue, $showElements, $hideElements;
selectedValue = $(this).val();
$hideElements = $(this).parents(".image_video_sec").find(".image_sec, .video_sec");
$hideElements.hide().find("input").attr('disabled', true);
if (selectedValue == "0") {
$showElements = $(this).parents(".image_video_sec").find(".image_sec");
} else if (selectedValue == "1") {
$showElements = $(this).parents(".image_video_sec").find(".video_sec");
}
$showElements.show().find("input").attr('disabled', false);
};
.image_sec,
.video_sec {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>

How to use querySelectorAll to disable a button if all radios in a div have not been checked?

I have the following page which I would like to force the user to check all the radios in the first view:
function show(shown, hidden) {
document.getElementById(shown).style.display = 'block';
document.getElementById(hidden).style.display = 'none';
document.querySelector('[data-testid="crowd-submit"]').style.display = 'inline-block';
return false;
}
function enableButton() {
if (document.querySelectorAll("link[type^=radio]:checked") !== null) {
document.getElementById('button').disabled = false;
}
}
[data-testid="crowd-submit"] {
display: none;
}
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
<crowd-form answer-format="flatten-objects">
<!-- Start Page number one (part 1) -->
<div id="Page1">
<h2>Part 1/2</h2>
<div class="container">
<h4> this is question 1?</h4>
<input type="radio" value="val1" name="question1_1" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question1_1" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question1_1" required onclick="enableButton()">C</input>
<i></i>
</div>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question2_2" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question2_2" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question2_2" required onclick="enableButton()">C</input>
<i></i>
</div>
<button type="button" id="button" class="d-block mr-0 ml-auto" disabled onclick="return show('Page2','Page1');"><b>Next</b></button>
<br>
<br>
</div>
<!-- End Page number one (part 1) -->
<!-- start Page number two (part 2) -->
<div id="Page2" style="display:none">
<h2>Part 2/2</h2>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question3_3" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question3_3" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question3_3" required onclick="enableButton()">C</input>
<i></i>
</div>
</div>
</crowd-form>
How can I disable the next button, until all the radios in the first view have not been answered?
So far, what I tried was:
document.querySelectorAll("link[type^=radio]:checked") !== null
And
if (document.querySelectorAll("link[type^=radio]:checked").length !== null) {
document.getElementById('button').disabled = false;
}
}
And with Jquery:
$(function(){
$("input[type='radio']").change(function(){
$("input[type='submit']").prop("disabled", false);
});
});
However, these attemps have not worked, because if you answer only one set of radios in the first view, the website allows you to continue with the second one. How can I disable the next button, until all the checkboxes in the first view have been completed?
What is even link in link[type^=radio]?
its input[type^=radio]
Also if you are checking .length you need to compare it to an number not null...
.length Always returns an number, 0 >
.length !== 0
function show(shown, hidden) {
document.getElementById(shown).style.display = 'block';
document.getElementById(hidden).style.display = 'none';
document.querySelector('[data-testid="crowd-submit"]').style.display = 'inline-block';
return false;
}
function enableButton() {
console.log(document.querySelectorAll("input[type^=radio][name=question1_1]:checked").length)
console.log(document.querySelectorAll("input[type^=radio][name=question1_2]:checked").length)
if (document.querySelectorAll("input[type^=radio][name=question1_1]:checked").length !== 0 && document.querySelectorAll("input[type^=radio][name=question2_2]:checked").length !== 0) {
document.getElementById('button').disabled = false;
}
}
[data-testid="crowd-submit"] {
display: none;
}
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
<crowd-form answer-format="flatten-objects">
<!-- Start Page number one (part 1) -->
<div id="Page1">
<h2>Part 1/2</h2>
<div class="container">
<h4> this is question 1?</h4>
<input type="radio" value="val1" name="question1_1" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question1_1" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question1_1" required onclick="enableButton()">C</input>
<i></i>
</div>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question2_2" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question2_2" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question2_2" required onclick="enableButton()">C</input>
<i></i>
</div>
<button type="button" id="button" class="d-block mr-0 ml-auto" disabled onclick="return show('Page2','Page1');"><b>Next</b></button>
<br>
<br>
</div>
<!-- End Page number one (part 1) -->
<!-- start Page number two (part 2) -->
<div id="Page2" style="display:none">
<h2>Part 2/2</h2>
<div class="container">
<h4> this is question 2?</h4>
<input type="radio" value="val1" name="question3_3" required onclick="enableButton()">A</input>
<input type="radio" value="val2" name="question3_3" required onclick="enableButton()">B</input>
<input type="radio" value="val3" name="question3_3" required onclick="enableButton()">C</input>
<i></i>
</div>
</div>
</crowd-form>
If you want to use 0 as compression just use more direct CSS targeting and add one more condition:
if (document.querySelectorAll("input[type^=radio][name=question1_1]:checked").length !== 0 && document.querySelectorAll("input[type^=radio][name=question2_2]:checked").length !== 0)
so you can put in those two groups any number of options, and in each at least one needs to be picked.
You need to check for the number of radio buttons that are checked, right now you are just checking if any radio buttons are checked.
function enableButton() {
// check if both radio buttons are checked
if (document.querySelectorAll("link[type^=radio]:checked").length == 2) {
document.getElementById('button').disabled = false;
}
}

Show and Hide contents base on radio button selection in jQuery

I am trying to display different contents base on radio button select in jquery.
My HTML is something like this:
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" name="b_type" value="1" <?=(isset($type) && $type == 'Person') ? ' checked' : ''?>> Person
</label>
<label class="radio-inline">
<input type="radio" name="b_type" value="2" <?=(isset($type) && $type == 'Institute') ? ' checked' : ''?>> Institute
</label>
</div>
This is how I tried in jquery to display two different contents for each radio button selection.
$('input[type="radio"][name="b_type"]').on('change',function(){
var sel = $(this);
if(sel.val() == 1){
$('#person-block').show();
$('#person-institute').show();
}else{
$('#institute-block').show();
$('#person-block').hide();
});
This code is working in some way. But there is a problem. Default radio button checked is dynamic. Lets assume second button is checked when the page is loading, then it display #persion-block contents. But I want to display #institute-block contents.
If I click on first button and then click on second its working.
Can anybody tell me how to figure this out?
Thank you.
Just trigger the change event in the element inside the document.ready
Note : You have some id typo .
$('input[type="radio"][name="b_type"]').on('change',function(){
alert($(this).val());
if($(this).val() == "1"){
$('#person-block').show();
$('#institute-block').hide();
}else{
$('#institute-block').show();
$('#person-block').hide();
}
});
$(document).ready(function(){
$('input[type="radio"][name="b_type"]:checked').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" name="b_type" value="1" > Person
</label>
<label class="radio-inline">
<input type="radio" name="b_type" value="2" checked> Institute
</label>
</div>
<div id="person-block" >
Person
</div>
<div id="institute-block" >
Institute
</div>
You can check which button is checked on page load with the :checked pseudo class (additionally to your existing event handler):
if ($('input[type="radio"][name="b_type"]:checked').val() == 1) {
$('#person-block').show();
} else {
$('#institute-block').show();
}
.block {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" name="b_type" value="1" > Person
</label>
<label class="radio-inline">
<input type="radio" name="b_type" value="2" checked> Institute
</label>
</div>
<div id="person-block" class="block">
Person
</div>
<div id="institute-block" class="block">
Institute
</div>
Additionally I would recommend hiding both elements on default to avoid showing the content of both before the JS has been loaded.
$(document).ready(function () {
$('input[type="radio"][name="b_type"]').on('change', function () {
var sel = $(this).filter(':checked').val();
if (sel == 1) {
$('#person-block').show();
$('#institute-block').hide();
} else {
$('#institute-block').show();
$('#person-block').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" name="b_type" value="1" > Person
</label>
<label class="radio-inline">
<input type="radio" name="b_type" value="2" checked> Institute
</label>
</div>
<div style="display:none" id="person-block" class="block">
Person
</div>
<div style="display:none" id="institute-block" class="block">
Institute
</div>
use .is(':checked')
if($('#myradiobutton').is(':checked')){
// this
}else{
// that
}
$("#redio1").click(function(){
$('#person-block').css('display','block');
$('#person-institute').css('display','block');
})
$("#redio2").click(function(){
$('#institute-block').css('display','block');
$('#person-block').css('display','none');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" id="redio1" name="b_type" value="1" <?=(isset($type) && $type == 'Person') ? ' checked' : ''?>> Person
</label>
<label class="radio-inline">
<input type="radio" id="redio2" name="b_type" value="2" <?=(isset($type) && $type == 'Institute') ? ' checked' : ''?>> Institute
</label>
</div>
<div id="person-block" style="color:red;display:none;">person-block</div>
<div id="person-institute" style="color:black;display:none;">person-institute</div>
$(document).ready(function () {
$('input[type="radio"][name="b_type"]').on('change', function () {
var sel = $(this).filter(':checked').val();
if (sel == 1) {
$('#person-block').show();
$('#institute-block').hide();
} else {
$('#institute-block').show();
$('#person-block').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" name="b_type" value="1" <?=(isset($type) && $type == 'Person') ? ' checked' : ''?> Person
</label>
<label class="radio-inline">
<input type="radio" name="b_type" value="2" <?=(isset($type) && $type == 'Institute') ? ' checked' : ''?>Institute
</label>
</div>
<div style="display:none" id="person-block" class="block">
Person
</div>
<div style="display:none" id="institute-block" class="block">
Institute
</div>

Progress bar not working on HTML page

I'm using javascript and HTML to create a questionnaire form. My idea was to inform the user of how many questions they've got to go. I've tried a couple of ways of getting a progress bar to work which has led me to the code below. I want the bar to progress after the user has selected an answer to a question.
This is the javascript code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script>
var progress = 0;
//need this to check if the question has not been answered before
var questions = {
"q1": 0,
"q2":0,
"q3":0,
"q4":0
}
$( function() {
$("#progressbar-1").text(progress)
$("input, select").change( function() {
el_name = $(this).attr("name");
switch (this.nodeName.toLowerCase()) {
case "select":
field =$("[name='"+el_name+"']");
val = (field.val() === "" || !field.val()) ? null: field.val();
break;
case "input":
field =$("[name='"+el_name+"']:checked");
val = field.length;
break;
}
if (val) {
if (!questions[el_name]) {
progress = progress +1;
questions[el_name]=1
}
} else {
questions[el_name]=0
progress = (progress > 0)?progress-1:0;
}
$("#progressbar-1").text(progress)
})
})
</script>
This is the HTML code.
<div class="container-main bg-5">
<button style="float:left" onclick="goBack()">Go Back</button>
<h1>What IT sector could suit you</h1>
<p>Take the questionnaire below!</p>
<form id="quiz">
<!-- Question 1 -->
<h2>Do you enjoy fixing things</h2>
<!-- Here are the choices for the first question. Each input tag must have the same name. For this question, the name is q1. -->
<!-- The value is which answer the choice corresponds to. -->
<label>
<input type="radio" name="q1" id="q1" value="c1">
Yes
</label><br />
<label>
<input type="radio" name="q1" id="q1" value="c2">
No
</label><br />
<label>
<input type="radio" name="q1" id="q1" value="c3">
Maybe
</label><br />
<!-- Question 2 -->
<h2>Do you enjoy problem solving?</h2>
<!-- Here are the choices for the second question. Notice how each input tag has the same name (q2), but a different name than the previous question. -->
<label>
<input type="radio" name="q2" value="c2">
Yes
</label><br />
<label>
<input type="radio" name="q2" value="c1">
No
</label><br />
<label>
<input type="radio" name="q2" value="c3">
Unsure
</label><br />
<!-- Question 3 -->
<h2>Do you enjoy maths?</h2>
<!-- Choices for the third question -->
<label>
<input type="radio" name="q3" value="c2">
Yes
</label><br />
<label>
<input type="radio" name="q3" value="c1">
No
</label><br />
<label>
<input type="radio" name="q3" value="c3">
Unsure
</label><br />
<!-- Question 4 -->
<h2>Do you often take thing apart to rebuild them?</h2>
<!-- Choices for the fourth question -->
<label>
<input type="radio" name="q4" value="c1">
Yes
</label><br />
<label>
<input type="radio" name="q4" value="c2">
No
</label><br />
<label>
<input type="radio" name="q4" value="c3">
I have never done it before so i don't know
</label><br />
<!--Question 5 -->
<h2>Hardware or Software?</h2>
<label>
<input type="radio" name="q5" value="c1">
Hardware
</label><br />
<label>
<input type="radio" name="q5" value="c2">
Software
</label><br />
<button type='button' id="submit" onclick="tabulateAnswers()">Submit Your Answers</button>
<button type="reset" id="reset" onclick="resetAnswer()">Reset</button>
</form>
<div id ="progressbar-1"></div>
</div>
The number is increasing but no CSS is happening. I feel like i'm not doing something glaringly obvious.
I have updated your progress bar HTML, JavaScript code and add some CSS.
Progress Bar HTML:
<div class="progress_dashv2">
<div id="progressbar-1"> </div>
</div>
JQuery Code:
var total_questions = 4;
// progress bar Calculation
var result = progress / total_questions;
result = result * 100;
$("#progressbar-1").css({'width':result+'%','background-color':'red'});
$("#progressbar-1").text(progress);
CSS Classes :
.progress_dashv2 {
margin-top: 0px;
background: #464646;
width: 100%;
float: left;
border-radius: 3px;
height: 30px;
}
#progressbar-1{
line-height: 11px;
padding: 10px;
border-radius: 3px;
}
Please refer to the following link (Your Example):
https://jsfiddle.net/fd8sntu8/1/

How can I make this javascript form validation DRYer?

The user has to select one radio from each of three input "categories". If he "submits" without doing so, he gets a warning:
http://jsfiddle.net/bqyvS/
Markup like this:
<form>
<div id="color">
<input type="radio" name="color" id="blue">
<label for="blue">Blue</label>
<input type="radio" name="color" id="red">
<label for="red">Red</label>
<input type="radio" name="color" id="green">
<label for="green">Green</label>
</div>
<div id="shape">
<input type="radio" name="shape" id="square">
<label for="square">Square</label>
<input type="radio" name="shape" id="circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" id="triangle">
<label for="triangle">Triangle</label>
</div>
<div id="size">
<input type="radio" name="size" id="small">
<label for="small">Small</label>
<input type="radio" name="size" id="medium">
<label for="mediume">Medium</label>
<input type="radio" name="size" id="large">
<label for="large">Large</label>
</div>
</form>
<a id="link" href="#">click me to "submit"</a>
<p id="warning"></p>​
Javascript:
$('#link').on('click', function() {
if (!$('#color input[type=radio]:checked').length) {
$('#warning').html("Oops! Please choose a color!");
}
else if(!$('#shape input[type=radio]:checked').length) {
$('#warning').text("Oops! Please choose a shape!");
}
else if(!$('#size input[type=radio]:checked').length) {
$('#warning').text("Oops! Please choose a size!");
}
});
This is a simplified version of a larger piece of code. How can I rewrite the conditional more efficiently so that I'm not verbosely checking each input name? (There should only be one "warning" displayed per "submit", even if multiple input name categories aren't checked.) Editing the markup would be okay.
Thanks!
When applying behavior to similar groups, you should start thinking about classes instead of ids, in this solution, you don't need a separate data-name but I believe it's better to have data separate from html id, but you could use this.id if you prefer
<form>
<div id="color" class="selection-group" data-name="color">
<input type="radio" name="color" id="blue">
<label for="blue">Blue</label>
<input type="radio" name="color" id="red">
<label for="red">Red</label>
<input type="radio" name="color" id="green">
<label for="green">Green</label>
</div>
<div id="shape" class="selection-group" data-name="square">
<input type="radio" name="shape" id="square">
<label for="square">Square</label>
<input type="radio" name="shape" id="circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" id="triangle">
<label for="triangle">Triangle</label>
</div>
<div id="size" class="selection-group" data-name="size">
<input type="radio" name="size" id="small">
<label for="small">Small</label>
<input type="radio" name="size" id="medium">
<label for="mediume">Medium</label>
<input type="radio" name="size" id="large">
<label for="large">Large</label>
</div>
</form>
<a id="link" href="#">click me to "submit"</a>
<p id="warning"></p>​
Javascript:
$('#link').on('click', function() {
$('.selection-group').each(function() {
if(!$(this).find('input[type=radio]:checked').length) {
$('#warning').html("Oops! Please choose a "+ $(this).data('name') +"!");
return false;
}
});
});
function validationCheck() {
var isValid = true,
errorText = "";
$("form div").each( //get the divs that hold the radios and loop
//$("#color, #shape, #size").each( //could do it by ids of the divs also
function(){
var div = jQuery(this), //div reference
isChecked = div.find('input[type="radio"]:checked').length>0; //see if we have anything selected
if (!isChecked) { //if no selections, show error message
isValid = false; //set validation to false
errorText = "Oops! Please choose a " + div.prop("id") + "!"; //build error message
return false; //exit each loop
}
}
);
$('#warning').text(errorText); //set error message
return isValid;
}
$('#link').on('click', function(){
$('#color, #shape, #size').each(function(i, ele){
if($(this).find('input:checked').length == 0)
$('#warning').text("Oops! Please choose a " + this.id + "!");
});
});
jsFiddle
You may want to consider generating a warning message in the case a user does not select any inputs or only 1 input.
In this example, a user will recieve a message similar to Oops! Please choose a color, and shape!
$('#link').on('click', function(){
var msgs = [];
$('#color, #shape, #size').each(function(i, ele){
if($(this).find('input:checked').length == 0)
msgs.push(this.id);
});
if(msgs.length > 0)
$('#warning').text("Oops! Please choose a " + msgs.join(", and "));
});
jsFiddle

Categories