I am stuck at one point and unable to proceed further. I am trying to implement something like this below. The idea is to implement this,
If the checked checkbox length is greater than 2, then display the count else display the values of checkboxes. I am able to succeed in the checked checkboxes but unable to achieve when the user first checks the checkboxes and then unchecks. Please see the snippet. The output that I need at any point is to check if checkboxes length is greater than 2 and then do suitable actions. Can you please provide some light on this?
checkboxLength = 0;
$('input[name="checkname[]"]').click(function() {
checkboxval = $(this).val();
if ($(this).prop("checked")) {
checkboxLength++;
if (checkboxLength > 2) {
$('.selecteditems').html('<span>' + checkboxLength + ' Options selected</span>');
} else {
$('.selecteditems').append('<span>' + checkboxval + '</span>');
}
} else {
checkboxLength = checkboxLength - 1;
$('.selecteditems').html('<span>' + checkboxLength + ' Options selected</span>');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selecteditems"></div>
<div class="containerdiv">
<input type="checkbox" name="checkname[]" value="Value 1">
<label for="checkbox1">Value 1</label>
<input type="checkbox" name="checkname[]" value="Value 2">
<label for="checkbox2">Value 2</label>
<input type="checkbox" name="checkname[]" value="Value 3">
<label for="checkbox3">Value 3</label>
<input type="checkbox" name="checkname[]" value="Value 4">
<label for="checkbox4">Value 4</label>
<input type="checkbox" name="checkname[]" value="Value 5">
<label for="checkbox5">Value 5</label>
</div>
I am stuck at the else part. ie. that is if the checkboxes are unchecked and the length is less than or equal to 2.
Here is one way you can achieve your goal:
const $cn = $('input[name="checkname[]"]');
$cn.on('change', function() {
const checkedLength = $cn.filter(':checked').length;
console.log( checkedLength );
const vals = $cn.filter(':checked').map((i,f) => f.value).get().join(',');
const output = checkedLength > 2 ? `${checkedLength} options selected.` : vals;
$('div.selecteditems').html( $('<span/>').text( output ) );
});
LIVE DEMO
$(function() {
const $cn = $('input[name="checkname[]"]');
$cn.on('change', function() {
const checkedLength = $cn.filter(':checked').length;
console.log( checkedLength );
const vals = $cn.filter(':checked').map((i,f) => f.value).get().join(',');
const output = checkedLength > 2 ? `${checkedLength} options selected.` : vals;
$('div.selecteditems').html( $('<span/>').text( output ) );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selecteditems"></div>
<div class="containerdiv">
<input type="checkbox" name="checkname[]" value="Value 1">
<label for="checkbox1">Value 1</label>
<input type="checkbox" name="checkname[]" value="Value 2">
<label for="checkbox2">Value 2</label>
<input type="checkbox" name="checkname[]" value="Value 3">
<label for="checkbox3">Value 3</label>
<input type="checkbox" name="checkname[]" value="Value 4">
<label for="checkbox4">Value 4</label>
<input type="checkbox" name="checkname[]" value="Value 5">
<label for="checkbox5">Value 5</label>
</div>
Here's my final code adding to the code which was given my #PeterKA
const $cn = $('input[name="checkname[]"]');
$cn.on('change', function() {
const checkedLength = $cn.filter(':checked').length;
const vals = $cn.filter(':checked').map((i, f) => f.value).get();
finalCheckedValue = '';
$.each(vals, function(index, checkedValue) {
finalCheckedValue += '<span>' + checkedValue + '</span>';
});
output = checkedLength > 2 ? `${checkedLength} options selected.` : finalCheckedValue;
$('div.selecteditems').html(output);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selecteditems"></div>
<div class="containerdiv">
<input type="checkbox" name="checkname[]" value="Value 1">
<label for="checkbox1">Value 1</label>
<input type="checkbox" name="checkname[]" value="Value 2">
<label for="checkbox2">Value 2</label>
<input type="checkbox" name="checkname[]" value="Value 3">
<label for="checkbox3">Value 3</label>
<input type="checkbox" name="checkname[]" value="Value 4">
<label for="checkbox4">Value 4</label>
<input type="checkbox" name="checkname[]" value="Value 5">
<label for="checkbox5">Value 5</label>
</div>
Please let me know if this approach is correct or do I have to do any modifications.
Related
I have created a function that checks other checkboxes on change. the function works but there is an error showing in console and the performance of the click is slow.
the issue comes from the .change(); . I have added this at the end in conditional statement, so that the values of the text inputs change dynamically.
Now if i remove the .change(); from follwoing, it works ok but then the values of the text inputs won't change.
if(this.checked) {
//Do stuff
$(this).closest('.multiple_checboxes_sets').find(".sms_groups [data-group='" + name + "']").prop( "checked", true ).change();
} else {
$(this).closest('.multiple_checboxes_sets').find(".sms_groups [data-group='" + name + "']").prop( "checked", false ).change();
}
the whole code JSFiddle
$(document).ready(function() {
$(".group_checkbox_all").change(function() {
if (this.checked) {
$(this).closest('.group_checboxes_set').find('.group_checkbox').prop("checked", true).change();
} else {
$(this).closest('.group_checboxes_set').find('.group_checkbox').prop("checked", false).change();
}
});
$(".group_checkbox").change(function() {
var val = $(this).val();
var name = $(this).data('group');
var checked = $(this).closest('.group_checboxes_set').find('.group_checkbox:checked').map(function() {
return $(this).val()
}).get();
var notchecked = $(this).closest('.group_checboxes_set').find('.group_checkbox:not(:checked)').map(function() {
return $(this).val()
}).get();
var checkedtext = $(this).closest('.group_checboxes_set').find('.group_checkbox:checked').map(function() {
return $(this).data('group')
}).get();
var notcheckedtext = $(this).closest('.group_checboxes_set').find('.group_checkbox:not(:checked)').map(function() {
return $(this).data('group')
}).get();
$(this).closest('.group_checboxes_set').find('.lbu_multilistsvalue').val(checked).change();
$(this).closest('.group_checboxes_set').find('.lbu_currentvalue').val(notchecked).change();
$(this).closest('.group_checboxes_set').find('.lbu_multiliststext').val(checkedtext).change();
$(this).closest('.group_checboxes_set').find('.lbu_currenttags').val(notcheckedtext).change();
if (this.checked) {
//Do stuff
$(this).closest('.multiple_checboxes_sets').find(".sms_groups [data-group='" + name + "']").prop("checked", true).change();
} else {
$(this).closest('.multiple_checboxes_sets').find(".sms_groups [data-group='" + name + "']").prop("checked", false).change();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="multiple_checboxes_sets">
<div class="group_checboxes_set">
<div class="form-check">
<input class="group_checkbox_all" data-group="All" id="all" type="checkbox" value="0000" />
<label class="form-check-label" for="all">All</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 1" id="1111" type="checkbox" value="1111" />
<label class="form-check-label" for="1111">Box 1</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 2" id="2222" type="checkbox" value="22222" />
<label class="form-check-label" for="2222">Box 2</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 3" id="3333" type="checkbox" value="3333" />
<label class="form-check-label" for="3333">Box 3</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 4" id="4444" type="checkbox" value="4444" />
<label class="form-check-label" for="4444">Box 4</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 5" id="55555" type="checkbox" value="5555" />
<label class="form-check-label" for="55555">Box 5</label>
</div>
<input type="text" class="form-control lbu_multilistsvalue" id="lbu_multilistsvalue" name="lbu_multilistsvalue">
<input type="text" class="form-control lbu_currentvalue" id="lbu_currentvalue" name="lbu_currentvalue">
<input type="text" class="form-control lbu_multiliststext" id="lbu_multiliststext" name="lbu_multiliststext">
<input type="text" class="form-control lbu_currenttags" id="lbu_currenttags" name="lbu_currenttags" value="">
</div>
<div class="group_checboxes_set sms_groups">
<div class="form-check">
<input class="group_checkbox_all" data-group="All" id="all1" type="checkbox" value="aaaa" />
<label class="form-check-label" for="all1">All</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 1" id="11112" type="checkbox" value="bbbb" />
<label class="form-check-label" for="11112">Box 1</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 2" id="22223" type="checkbox" value="cccc" />
<label class="form-check-label" for="22223">Box 2</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 3" id="33334" type="checkbox" value="dddd" />
<label class="form-check-label" for="33334">Box 3</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 4" id="44445" type="checkbox" value="eeee" />
<label class="form-check-label" for="44445">Box 4</label>
</div>
<div class="form-check">
<input class="group_checkbox" data-group="Box 5" id="555556" type="checkbox" value="ffff" />
<label class="form-check-label" for="555556">Box 5</label>
</div>
<input type="text" class="form-control lbu_multilistsvalue" id="lbu_multilistsvalue1" name="lbu_multilistsvalue">
<input type="text" class="form-control lbu_currentvalue" id="lbu_currentvalue1" name="lbu_currentvalue">
<input type="text" class="form-control lbu_multiliststext" id="lbu_multiliststext1" name="lbu_multiliststext">
<input type="text" class="form-control lbu_currenttags" id="lbu_currenttags1" name="lbu_currenttags" value="">
</div>
</div>
how do you propose to get the same approach working? with minimum code
Well you got me thinking how to, started playing around and things got little out of hand hehe.
So minimum code part is out of the game for now :) .
Not quite finished as I don't understand what was the main goal. But most of it is working. And no chnage and click events what soever invoked manually. Its all based on arrays and pure JS.
And given your version is not working properly (looping problem) I will share this, hope it helps in understadning how to achive this in other way.
var group1 = [];
var group2 = [];
var group1Box = [];
var group2Box = [];
var itemvalue = [];
var itemvalue2 = [];
var itemBox = [];
//GROUP_CHECKBOX
document.querySelectorAll('input[type="checkbox"].group_checkbox').forEach(item => {
// GET ALL VALUES AND BOXES
if (item.classList.contains("group1") === true) {
group1.push(item.value);
group1Box.push(item.getAttribute('data-group'));
}
if (item.classList.contains("group2") === true) {
group2.push(item.value);
group2Box.push(item.getAttribute('data-group'));
}
// ADD EventListener TO ALL CHECKBOX
item.addEventListener('click', event => {
//IF GROUP1 CHECKBOX IS CHECKED
if (item.checked === true && item.classList.contains("group1") === true) {
itemvalue.push(item.value);
itemvalue2.push(document.querySelectorAll('input[type="checkbox"][data-group="' + item.getAttribute('data-group') + '"]')[1].value);
itemBox.push(item.getAttribute('data-group'));
group1 = group1.filter(group1 => !itemvalue.includes(group1));
group2 = group2.filter(group2 => !itemvalue2.includes(group2));
group1Box = group1Box.filter(group1Box => !itemBox.includes(group1Box));
document.getElementById("lbu_multilistsvalue").value = itemvalue;
document.getElementById("lbu_currentvalue").value = group1;
document.getElementById("lbu_multiliststext").value = itemBox;
document.getElementById("lbu_currenttags").value = group1Box;
document.querySelectorAll('input[type="checkbox"][data-group="' + item.getAttribute('data-group') + '"]')[1].checked = true;
document.getElementById("lbu_multilistsvalue1").value = itemvalue2;
document.getElementById("lbu_currentvalue1").value = group2;
document.getElementById("lbu_multiliststext1").value = itemBox;
document.getElementById("lbu_currenttags1").value = group1Box;
}
//IF GROUP1 CHECKBOX IS UN-CHECKED
if (item.checked === false && item.classList.contains("group1") === true) {
group1.push(item.value);
itemvalue = itemvalue.filter(itemvalue => !item.value.includes(itemvalue))
group2.push(document.querySelectorAll('input[type="checkbox"][data-group="' + item.getAttribute('data-group') + '"]')[1].value);
itemvalue2 = itemvalue2.filter(itemvalue2 => !document.querySelectorAll('input[type="checkbox"][data-group="' + item.getAttribute('data-group') + '"]')[1].value.includes(itemvalue2))
group1Box.push(item.getAttribute('data-group'));
itemBox = itemBox.filter(itemBox => !item.getAttribute('data-group').includes(itemBox))
document.getElementById("lbu_multilistsvalue").value = itemvalue;
document.getElementById("lbu_currentvalue").value = group1;
document.getElementById("lbu_multiliststext").value = itemBox;
document.getElementById("lbu_currenttags").value = group1Box;
document.querySelectorAll('input[type="checkbox"][data-group="' + item.getAttribute('data-group') + '"]')[1].checked = false;
document.getElementById("lbu_multilistsvalue1").value = itemvalue2;
document.getElementById("lbu_currentvalue1").value = group2;
document.getElementById("lbu_multiliststext1").value = itemBox;
document.getElementById("lbu_currenttags1").value = group1Box;
}
//IF GROUP2 CHECKBOX IS CHECKED
if (item.checked === true && item.classList.contains("group2") === true) {
itemvalue2.push(item.value);
itemBox.push(item.getAttribute('data-group'));
group2 = group2.filter(group2 => !itemvalue2.includes(group2));
group1Box = group1Box.filter(group1Box => !itemBox.includes(group1Box));
document.getElementById("lbu_multilistsvalue1").value = itemvalue2;
document.getElementById("lbu_currentvalue1").value = group2;
document.getElementById("lbu_multiliststext1").value = itemBox;
document.getElementById("lbu_currenttags1").value = group1Box;
}
//IF GROUP2 CHECKBOX IS UN-CHECKED
if (item.checked === false && item.classList.contains("group2") === true) {
group2.push(item.value);
itemvalue2 = itemvalue2.filter(itemvalue2 => !item.value.includes(itemvalue2))
group1Box.push(item.getAttribute('data-group'));
itemBox = itemBox.filter(itemBox => !item.getAttribute('data-group').includes(itemBox))
document.getElementById("lbu_multilistsvalue1").value = itemvalue2;
document.getElementById("lbu_currentvalue1").value = group2;
document.getElementById("lbu_multiliststext1").value = itemBox;
document.getElementById("lbu_currenttags1").value = group1Box;
}
})
})
//GROUP_CHECKBOX_ALL
document.querySelectorAll('input[type="checkbox"].group_checkbox_all').forEach(item => {
item.addEventListener('click', event => {
if (item.checked === true && item.classList.contains("group1all") === true) {
document.querySelectorAll('input[type="checkbox"].group_checkbox').forEach(item2 => {
item2.checked = true;
})
document.getElementById("lbu_multilistsvalue").value = itemvalue;
document.getElementById("lbu_currentvalue").value = group1;
document.getElementById("lbu_multiliststext").value = itemBox;
document.getElementById("lbu_currenttags").value = group1Box;
document.getElementById("lbu_multilistsvalue1").value = itemvalue2;
document.getElementById("lbu_currentvalue1").value = group2;
document.getElementById("lbu_multiliststext1").value = itemBox;
document.getElementById("lbu_currenttags1").value = group1Box;
}
if (item.checked === false && item.classList.contains("group1all") === true) {
document.querySelectorAll('input[type="checkbox"].group_checkbox').forEach(item2 => {
item2.checked = false;
})
document.getElementById("lbu_multilistsvalue").value = "";
document.getElementById("lbu_currentvalue").value = "";
document.getElementById("lbu_multiliststext").value = "";
document.getElementById("lbu_currenttags").value = "";
document.getElementById("lbu_multilistsvalue1").value = "";
document.getElementById("lbu_currentvalue1").value = "";
document.getElementById("lbu_multiliststext1").value = "";
document.getElementById("lbu_currenttags1").value = "";
}
if (item.checked === true && item.classList.contains("group2all") === true) {
document.querySelectorAll('input[type="checkbox"].group_checkbox.group2').forEach(item2 => {
item2.checked = true;
})
document.getElementById("lbu_multilistsvalue1").value = itemvalue2;
document.getElementById("lbu_currentvalue1").value = group2;
document.getElementById("lbu_multiliststext1").value = itemBox;
document.getElementById("lbu_currenttags1").value = group1Box;
}
if (item.checked === false && item.classList.contains("group2all") === true) {
document.querySelectorAll('input[type="checkbox"].group_checkbox').forEach(item2 => {
item2.checked = false;
})
document.getElementById("lbu_multilistsvalue1").value = "";
document.getElementById("lbu_currentvalue1").value = "";
document.getElementById("lbu_multiliststext1").value = "";
document.getElementById("lbu_currenttags1").value = "";
}
})
})
<div class="multiple_checboxes_sets">
<div class="group_checboxes_set">
<div class="form-check">
<input class="group_checkbox_all group1all" data-group="All" id="all" type="checkbox" value="0000" />
<label class="form-check-label" for="all">All</label>
</div>
<div class="form-check">
<input class="group_checkbox group1" data-group="Box 1" id="1111" type="checkbox" value="1111" />
<label class="form-check-label" for="1111">Box 1</label>
</div>
<div class="form-check">
<input class="group_checkbox group1" data-group="Box 2" id="2222" type="checkbox" value="22222" />
<label class="form-check-label" for="2222">Box 2</label>
</div>
<div class="form-check">
<input class="group_checkbox group1" data-group="Box 3" id="3333" type="checkbox" value="3333" />
<label class="form-check-label" for="3333">Box 3</label>
</div>
<div class="form-check">
<input class="group_checkbox group1" data-group="Box 4" id="4444" type="checkbox" value="4444" />
<label class="form-check-label" for="4444">Box 4</label>
</div>
<div class="form-check">
<input class="group_checkbox group1" data-group="Box 5" id="55555" type="checkbox" value="5555" />
<label class="form-check-label" for="55555">Box 5</label>
</div>
<input type="text" class="form-control lbu_multilistsvalue" id="lbu_multilistsvalue" name="lbu_multilistsvalue">
<input type="text" class="form-control lbu_currentvalue" id="lbu_currentvalue" name="lbu_currentvalue">
<input type="text" class="form-control lbu_multiliststext" id="lbu_multiliststext" name="lbu_multiliststext">
<input type="text" class="form-control lbu_currenttags" id="lbu_currenttags" name="lbu_currenttags" value="">
</div>
<div class="group_checboxes_set sms_groups">
<div class="form-check">
<input class="group_checkbox_all group2all" data-group="All" id="all1" type="checkbox" value="aaaa" />
<label class="form-check-label" for="all1">All</label>
</div>
<div class="form-check">
<input class="group_checkbox group2" data-group="Box 1" id="11112" type="checkbox" value="bbbb" />
<label class="form-check-label" for="11112">Box 1</label>
</div>
<div class="form-check">
<input class="group_checkbox group2" data-group="Box 2" id="22223" type="checkbox" value="cccc" />
<label class="form-check-label" for="22223">Box 2</label>
</div>
<div class="form-check">
<input class="group_checkbox group2" data-group="Box 3" id="33334" type="checkbox" value="dddd" />
<label class="form-check-label" for="33334">Box 3</label>
</div>
<div class="form-check">
<input class="group_checkbox group2" data-group="Box 4" id="44445" type="checkbox" value="eeee" />
<label class="form-check-label" for="44445">Box 4</label>
</div>
<div class="form-check">
<input class="group_checkbox group2" data-group="Box 5" id="555556" type="checkbox" value="ffff" />
<label class="form-check-label" for="555556">Box 5</label>
</div>
<input type="text" class="form-control lbu_multilistsvalue" id="lbu_multilistsvalue1" name="lbu_multilistsvalue">
<input type="text" class="form-control lbu_currentvalue" id="lbu_currentvalue1" name="lbu_currentvalue">
<input type="text" class="form-control lbu_multiliststext" id="lbu_multiliststext1" name="lbu_multiliststext">
<input type="text" class="form-control lbu_currenttags" id="lbu_currenttags1" name="lbu_currenttags" value="">
</div>
</div>
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>
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>
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;
}
});
});
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