Javascript checkbox onChange - javascript

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.

Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />

function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});

Use an onclick event, because every click on a checkbox actually changes it.

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});

HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}

Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};

Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">

try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />

I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Related

JavaScript button that changes the value in the checkbox field

I am trying to create a button that when clicked replaces the value in the field true false. If we click the first time the field becomes true, if the second time the field becomes false. But I still can't get the results. The field only changes true.
Checkbox: <input type="checkbox" id="myCheck">
<button onclick="check()">Check Checkbox</button>
<script>
function check() {
var value = document.getElementById("myCheck");
if (value = "false") {
document.getElementById("myCheck").checked = true;
} else {
document.getElementById("myCheck").checked = false;
}
}
</script>
Avoid inline handlers ("onclick"). You can simplify this using:
const checkUncheck = () => {
const cb = document.querySelector("#myCheck");
cb.checked = !cb.checked;
};
document.querySelector("button").addEventListener("click", checkUncheck);
<input type="checkbox" id="myCheck" disabled>
<button>check/uncheck</button>
You need to check if the checked attribute of your checkbox is true or false.
Checkbox: <input type="checkbox" id="myCheck">
<button onclick="check()">Check Checkbox</button>
<script>
function check() {
var checkbox = document.getElementById("myCheck");
if (checkbox.checked !== true) {
checkbox.checked = true;
} else {
checkbox.checked = false;
}
}
</script>
Also, you can re-use the checkbox variable.

Unchecking of the checked checkboxes on another button click

I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

How to get an added value from multiple checkboxes in javascript/jquery?

I have multiple checkboxes added with a button. I want to assign a value of 150 for each checkbox that is checked. Maybe my logic is wrong, but i cant get it working. Ideas?
function getValues() {
var cost = 0;
var isChecked = $('.isLab').prop('checked');
$('.isLab').each(function () {
if (isChecked == true) {
cost = 150
}
});
alert(cost);
}
$('button').click(getValues);
function getValues() {
alert( $('.isLab:checked').length * 150 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="isLab"/> Item 1<br/>
<input type="checkbox" class="isLab"/> Item 2<br/>
<input type="checkbox" class="isLab"/> Item 3<br/>
<button>Get values</button>
Comments inline...
function getValues() {
var cost = 0;
$('.isLab').each(function (index, element) {
if (element.checked == true) { // reference current checkbox
cost += 150; // ADD to it!
}
});
alert(cost);
}

unselecting radio input selection

In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>

Categories