Manipulating label with checkboxes - javascript

Scenario:
Three unchecked check-boxes, each with different id and value.
An empty paragraph (or label) with id = par.
[CB1] has value 1.
[CB2] has value 2.
[CB3] has value 3.
Now, when I click cb1 -> 'par' gets and prints the value of cb1.
Clicking on cb3, 'par' gets the value of cb1+cb3.
Clicking cb1, 'par' subtracts the value of cb1 and so on.. I think you get the point.
How can I achieve this with only HTML and JavaScript (without jQuery).
<input type="checkbox" id="1" value="1" />
<input type="checkbox" id="2" value="2" />
<input type="checkbox" id="3" value="3" />
<p id="par"></p>

This will do it: jsfiddle example (updated to remove alert)
HTML:
<input type="checkbox" id="1" value="1" onclick='checkClicked(event)'/>
<input type="checkbox" id="2" value="2" onclick='checkClicked(event)'/>
<input type="checkbox" id="3" value="3" onclick='checkClicked(event)'/>
<p id="par"></p>
JavaScript:
function checkClicked(element)
{
var targetElement = element.target;
var newVal = targetElement.value;
if( !targetElement.checked )
{
newVal *= -1;
}
var currentVal = document.getElementById('par').innerHTML;
if( currentVal )
{
newVal = parseInt(currentVal) + parseInt(newVal);
}
document.getElementById('par').innerHTML = newVal;
}

<label>
<input type="checkbox" id="check1" value="check1" onchange="alterP(this);"/>check1
</label>
<label>
<input type="checkbox" id="check2" value="check2" onchange="alterP(this);"/>check2
</label>
<label>
<input type="checkbox" id="check3" value="check3" onchange="alterP(this);"/>check3
</label>
<p id="par"></p>
js Code
function alterP(obj) {
var par = document.getElementById('par');
var txt = (obj.checked) ? obj.value : "";
par.innerHTML = txt;
}

<script>
document.getElementById("1").addEventListener("click", processCheck);
document.getElementById("2").addEventListener("click", processCheck);
document.getElementById("3").addEventListener("click", processCheck);
function processCheck() {
var theParagraph = document.getElementById("par");
var currentValue = 0;
if (!isNaN(parseInt(theParagraph.textContent))) {
currentValue = parseInt(theParagraph.textContent)
}
if (this.checked) {
theParagraph.textContent = currentValue + parseInt(this.value);
}
else {
theParagraph.textContent = currentValue - parseInt(this.value);
}
}
</script>

Related

Use values of checkbox based on which is checked, in variable

I would like to make a variable which has the values of 1 or multiple checkboxes, based on which one is selected. This is what I came up with for now:
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
var showvalue = document.getElementById("show-value");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
if (checkbox1.checked === true) {
showvalue.value = checkbox1.value;
}
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="hidden"/>
But I don't know how to iterate through checkboxes and if the specific one is checked, add it to variable showvalue. So what I want for showvalue is something like this (based on which checkbox is checked):
var showvalue = checkbox1.value + ", " + checkbox2.value + ", " + checkbox3.value;
How do I iterate through checkboxes and then if checked = true add that value to showvalue?
For showing I delete the hidden from the showvalue-inputfield and set it to readonly.
For calculating the result I go with foreach through the checkboxes and add if checked to the resultstring the value. The separator , is only set if there is already a partresult. After this at the end just update the value from showvalue.
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
var showvalue = document.getElementById("show-value");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
let value = '';
document.querySelectorAll('input[type=checkbox]').forEach(box => {
if (box.checked === true) {
if (value.length) value += ', ';
value += box.value;
}
});
showvalue.value = value;
}
.readonly { background: yellow;}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" size=40 class="readonly" readonly/>
you can try this:
var showvalue = document.getElementById("show-value");
var checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach(box => box.addEventListener('change', showValue));
function showValue() {
showvalue.value = Array.from(checkboxes).map(e => e.checked ? e.value : null).filter(Boolean).join(", ");
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="text"/>
Just use querySelector and use name attribute to check for what is checked or not. An example:
let result = [];
const setup = () => {
const entry1 = document.querySelectorAll('[name="entry1"]');
entry1.forEach(input => input.addEventListener('change', onChange));
}
const onChange = () => {
const checkedEntry1 = document.querySelectorAll('[name="entry1"]:checked');
result = [];
checkedEntry1.forEach(input => result.push(input.value));
document.querySelector('#show-value').value = result.join(', ');
}
//load
window.addEventListener('load', setup);
<input id="value1" name="entry1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" name="entry1" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" name="entry1" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show-value" type="hidden">
Is it that what you were looking for?
var checkbox1 = document.getElementById("value1");
var checkbox2 = document.getElementById("value2");
var checkbox3 = document.getElementById("value3");
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('change', showValue));
function showValue() {
if (checkbox1.checked === true) {
var box1 = checkbox1.value;
}else{
var box1 = '';
}
if (checkbox2.checked === true) {
var box2 = checkbox2.value;
}else{
var box2 = '';
}
if (checkbox3.checked === true) {
var box3 = checkbox3.value;
}else{
var box3 = '';
}
document.getElementById("show").value = box1 + ';' + box2 + ';' + box3;
}
<input id="value1" type="checkbox" value="3 maanden"><label for="value1">Value 1</label>
<input id="value2" type="checkbox" value="6 maanden"><label for="value2">Value 2</label>
<input id="value3" type="checkbox" value="Uitgeschreven"><label for="value3">Value 3</label>
<input id="show" class="readonly" readonly/>
document.querySelectorAll('input[type=checkbox]')
.forEach(box => box.addEventListener('input', showValue));
function showValue(event) {
var input = event.target;
var showvalue = document.getElementById('show-value');
showvalue.value += input.value;
// tern if statment
input.checked ? showvalue.type = 'text' : showvalue.type = 'hidden';
// you can used the original if statment
if (input.checked) {
showvalue.type = 'text';
} else {
showvalue.type = 'hidden';
}
}

jquery add / remove item from array

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>

Alert when selected similar value from multiple check box with the same class name

When I select for a second time from the below check box with the same value it should alert 'value is already checked' How do I do that using jquery?
<div>
<input type="checkbox" class="check" value="1"/>
</div>
<div>
<input type="checkbox" class="check" value="2"/>
</div>
<div>
<input type="checkbox" class="check" value="1"/>
</div>
<div>
<input type="checkbox" class="check" value="3"/>
</div>
<div>
<input type="checkbox" class="check" value="4"/>
</div>
<div>
<input type="checkbox" class="check" value="3"/>
</div>
I tried with below code but nothing is working
var itemVal=false;
$(document).on('change','.check:checked',function(){
selVal=$(this).val();
$('.check:checked').each(function(){
if($(this).val()==selVal)
itemVal=true;
});
if(itemVal==true){
alert('Proceed');
}else{
alert('Please choose same name');
}
});
Try this:
$('.check').change(function(event){
var arr = $(".check:checked").map(function() {
return $(this).val();
}).get();
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
if(results.length >0){
alert('value is already checked')
}
});
Demo:
http://jsfiddle.net/9a8o37h0/1/
Like this:
$('.check').click(function () {
if(!this.checked)
alert("Value is already Checked");
});
If you want to keep it checked add this before the alert
this.checked = true;

Add the sum of from the value select of radiobutton

For instance, radiobutton one = value 1, radiobutton two = value 2.
Here is the code I have:
Script file:
<script type="text/javascript">
$(document).ready(function () {
$("div[data-role='footer']").prepend('Back');
$(".Next").click(function () {
$.mobile.changePage("#" + $("#Answer").val());
});
$("input[type=radio]").click(function () {
var answer = $(this).val();
$("#Answer").val(answer);
});
$('.Answer').live("click", function () {
var NextQuestionID = $(this).attr('NextQuestionId');
if (NextQuestionID == '') {
location.href = "/Surveys/Index";
}
$("#survey").load('/Questions/GetQuestion', { Id: NextQuestionID }, function () {
$('#answerInput').textinput();
$(".Answer").button();
});
});
});
and here is my markup:
<input type="radio" name="Answer" id="radio-choice-1" value="Question2" />
<input id="Answer" class="Answer" type="hidden" value="first" />
<div class="innerspacer">
Next
</div>
How do I assign the radio button as value from 1 to 4 and sum up the value for all the question?
There is a lot going on in your question and it is unclear what you want. I'm taking a guess and assuming you have a say 5 radio buttons and you want the 5th radio button value to be the sum of the other 4 values. Is that correct?
Here is an example of doing that: jsfiddle
HTML:
<div id="container">
<label>
<input type="radio" name="something" value="1">
A?
</label>
<label>
<input type="radio" name="something" value="3">
B?
</label>
<label>
<input type="radio" name="something" value="5">
C?
</label>
<label>
<input type="radio" name="something" value="">
All?
</label>
</div>
JavaScript:
$(document).ready(function() {
var choices = $('input[name="something"]');
var total = 0;
choices.each(function() {
var choice = $(this);
var value = parseInt(choice.val(), 10);
if (!isNaN(value)) {
total += value;
}
});
choices.filter(':last').val(total);
});
You will need to adapt this to your HTML.

Javascript help. Adding/removing form element to DOM

if radio button 2 is checked add input box into datesettings. How do i add an input box? If radio button 1 is checked do nothing but if button 2 was checked previously remove children. Can you help me
Thanks
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
//Remove o2 children
}
else if(o2.checked) {
//How do I add an input box?
}
}
<input type="radio" id="dateoption1" name="dateoption" value="1" onclick="CheckDateOptions();">
<input type="radio" id="dateoption2" name="dateoption" value="2" onclick="CheckDateOptions();">
<span id="datesettings">//Add input box here if dateoption2 is checked</span>
The simplest route would be:
<input type="radio" id="dateoption1" name="dateoption" value="1" ="ToggleDateOptions(true);" />
<input type="radio" id="dateoption2" name="dateoption" value="2" ="ToggleDateOptions(false);" />
<span id="datesettings">
<input type="text" id="dateSetting" />
</span>
<script>
function ToggleDateOptions(oneChecked) {
if(oneChecked)
{
$("#dateSetting").hide();
}
else
{
$("#dateSetting").show();
}
}
</script>
Or if you didn't want to use JQuery (Which is used above) you could do:
if(oneChecked)
{
document.getElementById("dateSetting").style.display = 'none';
}
else
{
document.getElementById("dateSetting").style.display = 'inline';
}
You can just use innerHTML to add the input field.
Something like this should work for you
<script type="text/javascript">
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.innerHTML = "";
} else if(o2.checked) {
eSettings.innerHTML = '<input type="text" name="field" />';
}
}
</script>
<input type="radio" id="dateoption1" name="dateoption" value="1" onclick="CheckDateOptions()"/>
<input type="radio" id="dateoption2" name="dateoption" value="2" onclick="CheckDateOptions()"/>
<span id="datesettings"></span>
Demo

Categories

Resources