Display all selected items from checkboxes - javascript

I am using this codepen as a basis.
HTML
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
jQuery
$("input").on("click", function() {
$("#log").html($("input:checked").val() + "");
});
I have changed the radio buttons to checkboxes - but I would like to alter the js so that every selected item is then shown at the bottom of the list, rather than just the first.
The purpose is for a self awareness exercise - i.e. the user could select all statements which apply to them from a long list, and then they get an output that narrows it down to just the ones they've chosen. The form response doesn't need to be saved/submitted anywhere.
How can this be done?

$( "input" ).on( "click", function(e) {
if(e.currentTarget.checked){
var div = document.createElement("p");
div.id=e.target.value+"1";
div.innerHTML=e.target.value;
var tar=document.getElementById("log");
tar.appendChild(div);
} else {
var tag = document.getElementById(e.target.value+"1");
tag.parentNode.removeChild(tag);
}
});
You can try this its working.
Now when you click orange displayed and unchecked removed.

You need to make a couple of changes
If want to be able to select multiple radio buttons, then either keep their names different or use checkboxes.
Maintain an attribute wasChecked to toggle the checked property.
You need to iterate the checked boxes and then get their values.
Demo
$("input").on("click", function(e) {
var val = [];
var wasChecked = $(this).attr( "wasChecked" ) == "true";
if ( wasChecked )
{
$(this).prop( "checked", false );
}
else
{
$(this).prop( "checked", true );
}
$(this).attr( "wasChecked", $(this).prop( "checked") );
$("input:checked").each( function(){
val.push( $(this).val() );
});
$("#log").html( val.join( "," ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="radio" name="fruit1" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit2" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit3" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>

a lot of jQuery function like .val() are designed to operate on a single element, i.e., $("input#first-name").val(), and so only return the value for the first element matched if there are multiple matches.
you will probably need a loop to extract a value for each element. fortunately, jQuery provides a function to do this as well.
$( "input" ).on( "click", function() {
var html = "";
$( "input:checked" ).each(function() {
// "this" in this context is the jQuery element in this position in the list
html += $(this).val() + "";
}
$( "#log" ).html(html);
});

$( ":checkbox" ).on('change',function(){
var li_id = 'li_'+$(this).attr('id');
if(this.checked){
$('#list').append("<li id="+li_id+">"+$(this).val()+"</li>")
}else{
$('#'+li_id).remove();
}
})
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<ul id='list'>
</ul>
This is just a simple example to add and remove items from the list if they're checked or not. At least it gives you an idea on how you can achieve it.

Now you have an array. So, maybe you need something like this?
$( "input" ).on( "click", function() {
var selectedItems = $( "input:checked" );
var results = "";
for(var i = 0; i < selectedItems.length; i++){
if(i > 0) results += ", ";
results += selectedItems[i].value;
}
$( "#log" ).html( results );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>

function add(element)
{
var fruits=document.getElementById("log").innerHTML;
var fruit=element.value;
if(fruits=="")
{
document.getElementById("log").innerHTML = fruit.toString();
}
else
{
if(document.getElementById(element.id).checked == true)
{
fruits= fruits+' '+fruit.toString();
}
else
{
fruits = fruits.replace(element.value,'');
}
document.getElementById("log").innerHTML=fruits;
}
}
<form>
<div>
<input type="checkbox" value="orange" id="orange" onclick="add(this);">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" value="apple" id="apple" onclick="add(this);">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" value="banana" id="banana" onclick="add(this);">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>

Plain JavaScript solutions:
With one loop:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked"),
res = new Array(checkboxes.length);
function checkChecked() {
[].forEach.call(checkboxes, (checkbox, i) => {
checkbox.addEventListener("change", function() {
checkbox.checked ? res[i] = checkbox.value : res[i] = "";
checked.innerHTML = res.join(",").replace(/(^[,]+)|([,]+$)/g, "").replace(/(,){2,}/g, ",");
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
With two loops:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked");
function getResult() {
var res = "";
[].forEach.call(checkboxes, checkbox => {
checkbox.checked ? res += checkbox.value + "," : false
})
res = res.replace(/(,$)/, "");
return res;
}
function checkChecked() {
[].forEach.call(checkboxes, checkbox => {
checkbox.addEventListener("change", function() {
checked.innerHTML = getResult();
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>

Related

Event listeners for both radio buttons and text input

I have a group of radio buttons and a text input field:
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
And I wanna the result of final price calculated by Price * Discount and updating the <p id="resultToast"> </p>.
So I did
const radios = document.querySelector('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
From the console, the radios.value not updated correctly after clicking the radio buttons. What I did wrong?
Just change:
const radios = document.querySelector('input[name="discount"]:checked');
To:
const radios = document.querySelectorAll('input[name="discount"]:checked');
See working snippet:
const radios = document.querySelectorAll('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
Reason for this is because you stored the initial
document.querySelector('input[name="discount"]:checked');
value as radios. Now that we look for all, it changes accordingly.
You are referring to a constant you defined at the beginning of your script. This will always give you the same radio button value (the one being checked at the beginning). Do something like
let discount=document.querySelector("input[name=discount]:checked").value
within your event handler function to get the current value of the radio button group.
You could also declutter(=shorten) your code a bit and make it reusable for multiple input sections that way, see below:
function qs(sel,el){return (el||document).querySelector(sel);}
function makeInteractive(frmsel){
const frm=qs(frmsel),
prc=qs("[name=price]",frm),
res=qs(".result",frm);
frm.onchange=calc;
frm.oninput= calc;
function calc(){
res.textContent=
(prc.value * qs("[type=radio]:checked",frm).value)
.toFixed(2);
}
}
makeInteractive("#frm1");
makeInteractive("#frm2");
<form id="frm1">
the first item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>
<form id="frm2">
the second item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>

Add values from checkbox labels

I have 4 checkboxes with labels and a total label in my webpage. The labels are the price e.g. $12, $100. When the user checks a box I want to take the value from the label and put it in the total label. Then if the user deselect the box, then subtract that value from the total label.
I have tried to set a function called checkbox2() where I took the value and stripped the '$' then turned the remaining string into a number. Then checked if the box was checked, if so, then add number. then convert back to string and set the innerHTML. Did not work and I am sure not the way to do this.
How should I go about this?
<div class="cbwrap">
<label for="check2" name="label2" id="label2">
<input type="checkbox" class="cb" id="check2" onclick="checkBox2()"/> $125
</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" id="check3" onclick="checkBox2()"/> $100
</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" onclick="checkBox2()" /> $75
</label>
</div>
<div class ="cbwrap">
<label>
<input type="checkbox" class="cb" onclick="checkBox2()" /> $50
</label>
</div>
<div class ="pwrap">
<p class="cat1"><b><u>Total</u></b></p>
</div>
<div class="cbwrap">
<label for="total" name="totallbl" id="totallbl"><u><b>$0</b></u></label>
</div>
<div>
<label for="total" name="agreedLBL" id="agreedLBL">0</label>
</div>
JS:
var k = document.getElementById("totallbl").innerHTML;
if (document.getElementById("check1").checked) {
x = "150";
} else {
x = "0";
var res = k + x;
document.getElementById("totallbl").innerHTML = res;
}
your html was also not correct. Try this
function checkBox2(checkbox) {
if (checkbox.checked) {
var value = checkbox.parentNode.textContent.match(/\s*\d+(?:\.\d{2})?/)[0];
var totalValue = document.getElementById('totallbl').querySelector('b').innerHTML.match(/\s*\d+(?:\.\d{2})?/)[0];
var newTotalValue = parseFloat(value) + parseFloat(totalValue);
document.getElementById('totallbl').querySelector('b').innerHTML = "$" + newTotalValue;
document.getElementById('agreedLBL').innerText = newTotalValue;
} else {
var value = checkbox.parentNode.textContent.match(/\s*\d+(?:\.\d{2})?/)[0];
var totalValue = document.getElementById('totallbl').querySelector('b').innerHTML.match(/\s*\d+(?:\.\d{2})?/)[0];
var newTotalValue = parseFloat(totalValue) - parseFloat(value);
document.getElementById('totallbl').querySelector('b').innerHTML = "$" + newTotalValue;
document.getElementById('agreedLBL').innerText = newTotalValue;
}
}
<div class="cbwrap">
<label for="check2" name="label2" id="label2">
<input type="checkbox" class="cb" id="check2" onclick="checkBox2(this)" /> $125</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" id="check3" onclick="checkBox2(this)" /> $100</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" onclick="checkBox2(this)" /> $75</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" onclick="checkBox2(this)" /> $50</label>
</div>
<div class="pwrap">
<p class="cat1"><b><u>Total</u></b></p>
</div>
<div class="cbwrap">
<label for="total" name="totallbl" id="totallbl"><u><b>$0</b></u></label>
</div>
<div>
<label for="total" name="agreedLBL" id="agreedLBL">0</label>
</div>
Basically, you should be setting html in a way so that it's easy to access values associated with checkboxes. Please note data-value="0" on totallbl and value assigned for each input checkbox.
function checkBox2(obj) {
var k = parseInt(document.getElementById("totallbl").dataset.value);
if (obj.checked) {
k += parseInt(obj.value);
} else {
k -= parseInt(obj.value);
}
document.getElementById("agreedLBL").innerHTML = k;
document.getElementById("totallbl").dataset.value = k;
document.getElementById("totallbl").innerHTML = '$' + k;
}
<div class="cbwrap"><label for="check1" name="label2" id="label2"><input type="checkbox" class="cb" id="check1" onclick="checkBox2(this);" value="150" /> $150</label></div>
<div class="cbwrap"><label for="check2" name="label2" id="label2"><input type="checkbox" class="cb" id="check2" onclick="checkBox2(this);" value="125" /> $125</label></div>
<div class="cbwrap"><label><input type="checkbox" class="cb" id="check3" onclick="checkBox2(this);" value="100" /> $100</label></div>
<div class="cbwrap"><label><input type="checkbox" class="cb" onclick="checkBox2(this);" value="75" /> $75</label></div>
<div class="cbwrap"><label><input type="checkbox" class="cb" onclick="checkBox2(this);" value="50" /> $50</label></div>
<div class="pwrap"><p class="cat1"><b><u>Total</u></b></p></div>
<div class="cbwrap"><label for="total" name="totallbl" id="totallbl" data-value="0" style="font-weight:bold;text-decoration:underline">$0</label></div>
<div> <label for="total" name="agreedLBL" id="agreedLBL">0</label></div>
HEllo Dear it complete running example and please add jquery cdn in head tag.
if you not getting exact output then tell me..
<body>
<div class="cbwrap">
<label for="check2" name="label2" id="label2">
<input type="checkbox" class="cb" id="check2" onclick="checkBox2(this)" />
$125</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" id="check3" onclick="checkBox2(this)" />
$100</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" onclick="checkBox2(this)" />
$75</label>
</div>
<div class="cbwrap">
<label>
<input type="checkbox" class="cb" onclick="checkBox2(this)" />
$50</label>
</div>
<div class="pwrap">
<p class="cat1">
<b><u>Total</u></b>
</p>
</div>
<div class="cbwrap">
<label for="total" name="totallbl" id="totallbl"><u><b>$0</b></u></label>
</div>
<div>
<label for="total" name="agreedLBL" id="agreedLBL">0</label>
</div>
<script>
function checkBox2(tempCheckBOx) {
var tempLenght = $(".cbwrap label input[type='checkbox']").length;
var tempTotal = 0;
for (var i = 0; i < tempLenght; i++) {
if ($(".cbwrap label input[type='checkbox']").eq(i).prop('checked') == true) {
var tempStore = $(".cbwrap label").eq(i).text();
var tempVal = parseInt(tempStore.trim().substr(1, (tempStore.length + 1)));
tempTotal += tempVal;
}
}
$("#agreedLBL").text("$"+tempTotal);
}
</script>
</body>
$(document).ready(function(){
$('.cb').click(function(){
var totalvaluestored = document.getElementById('totallbl').innerText.replace(/\$/g, '');
var value = this.value;
if(totalvaluestored === "0"){
document.getElementById('totallbl').innerHTML = '$'+value;
this.value = "";
}
else if(totalvaluestored !== "0" && value !== "")
{
value = parseInt(totalvaluestored) + parseInt(value);
document.getElementById('totallbl').innerHTML = '$ '+value;
this.value = "";
}
else{
var value = this.closest('label').innerText;
value = value.replace(/\$/g, '');
this.value = value;
value = parseInt(totalvaluestored) - parseInt(value);
document.getElementById('totallbl').innerHTML = '$ '+value;
}
});
});

Check box class based click function not working

I am trying to find out which check box is selected in a group of check boxes and read its value.
The following is the checkbox format
<div class="panel-body smoothscroll maxheight300 brand_select">
<div class="block-element">
<label>
<input type="checkbox" name="term" value="0" />
Armani </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="1" />
Gucci </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="2" />
Louis Vuitton </label>
</div>
</div>
I tried giving class names but it didn't work. I gave class names as class="brand_name" and tried to read through jquery click function
$('.brand_name').click(function () {
console.log("click worked")
});
But it didn't work. Can someone suggest me a way to do this.
You are applying the click event handler on div and not on checkboxes
$('.brand_select').on('click', ':checkbox', function() {
alert($(this).is(':checked'));
});
To get list of all checked values:
$('.brand_select').on('click', ':checkbox', function() {
var checkedEl = [];
$('.brand_name :checkbox').each(function () {
if ($(this).is(':checked')) {
checkedEl.push($(this).val());
}
});
console.log('Checked values');
console.log(checkedEl);
});
$('input[type="checkbox"]').on('click',function () {
if(this.checked){
alert($(this).val());
}else{
// .........
}
})
Add the class to input elements and change the name of the fields so that you can use them as array -
<input type="checkbox" name="term[]" value="2" class="brand_name"/>
Here is a possible solution:
$('input[name="term"]').on('change', function(){
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel-body smoothscroll maxheight300 brand_select">
<div class="block-element">
<label>
<input type="checkbox" name="term" value="0" />
Armani </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="1" />
Gucci </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="2" />
Louis Vuitton </label>
</div>
</div>

jQuery - Uncheck other checkboxes if a specific checkbox is selected by user

I would like to uncheck all the checkboxes that are presently selected if a specific checkbox is selected by the user.
Example:
<div>
<label for="foo">
<input type="checkbox" name="meh" id="foo" checked> foo
</label>
</div>
<div>
<label for="bar">
<input type="checkbox" name="meh" id="bar" checked> bar
</label>
</div>
<div>
<label for="foobar">
<input type="checkbox" name="meh" id="foobar"> foobar
</label>
</div>
<div>
<label for="barfoo">
<input type="checkbox" name="meh" id="barfoo" checked> barfoo
</label>
</div>
<div>
<label for="omgwtfbbq">
<input type="checkbox" name="meh" id="omgwtfbbq"> omgwtfbbq
</label>
</div>
If the user selects "omgwtfbbq" checkbox, I would like all the other boxes that might be checked to be unchecked and have the "omgwtfbbq" be the only one checked.
for the label instead of id I think you need for
<div>
<label for="foo">
<input type="checkbox" name="foo" id="foo" checked /> foo
</label>
</div>
<div>
<label for="bar">
<input type="checkbox" name="bar" id="bar" checked /> bar
</label>
</div>
<div>
<label for="foobar">
<input type="checkbox" name="foobar" id="foobar" /> foobar
</label>
</div>
<div>
<label for="barfoo">
<input type="checkbox" name="barfoo" id="barfoo" checked /> barfoo
</label>
</div>
<div>
<label for="omgwtfbbq">
<input type="checkbox" name="omgwtfbbq" id="omgwtfbbq" /> omgwtfbbq
</label>
</div>
then
var $others = $('input[type="checkbox"][name="meh"]').not('#omgwtfbbq')
$('#omgwtfbbq').change(function () {
if (this.checked) {
$others.prop('checked', false)
}
});
$others.change(function () {
if (this.checked) {
$('#omgwtfbbq').prop('checked', false)
}
})
Demo: Fiddle
Note: I'll add a common class to all the input elements which has to be affected by omgwtfbbq and change var $others = $('#foo, #bar, #foobar, #barfoo') to var $others = $('.myclassoninput')
Live demo (click).
$('#omgwtfbbq').click(function() {
$('input:checkbox').not(this).attr('checked', false);
});
Also note that you're re-using id's. Id's should only be used once in a document.
If you choose not to give each checkbox a sequential IDs so that you can use an array, here's a solution:
Place all your controls in a div, with an ID "checkgroup".
Then the JavaScript function goes:
function checkone(d){
if (!d.checked) return; //if it's unchecked, then do nothing
var group=document.getElementById('checkgroup');
var os=group.getElementsByTagName('input');
for (var i=0;i<os.length;i++){
if (os[i].checked&&os[i]!=d) os[i].checked=false;
}
}
Now you can call this function in each checkbox
<div id="checkgroup">
<input id="abcd" onclick="checkone(this);">
<input id="xyz" onclick="checkone(this);">
...
</div>
Note how you don't even need to bother with the name, because the object passes in itself.

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