Javascript onchange checkbox cancel - javascript

My first question here and really hope to learn a lot. I'm actually not the technical guy at my startup but cause of the lack of it trying to do things by myself :-)
I made an onchange event for my module order system. When i click on the checkbox, the selected module appears in the summary. This works. But when i deselect the checkbox, i want the module to dissapear from the summary. That doesn't work now. What do i have to change in the JS to do that?
The checkbox
<input type="checkbox" class="custom-control-input"
onchange="modulecontractsSelect(this, event)">
The summary
<p id="module-contracts-summary"> </p>
<p id="module-contracts-summary-price"> </p>
The Javascript
function modulecontractsSelect() {
document.getElementById("module-contracts-summary").innerHTML = "Module contractbeheer"
document.getElementById("module-contracts-summary-price").innerHTML = "€5 / mnd";
}
Thanks in advance!

First, change your checkbox's onchange event to pass only itlsef (as this) as a parameter. You don't really need to pass the event as a parameter:
<input type="checkbox" class="custom-control-input" onchange="modulecontractsSelect(this);">
Then, change your modulecontractsSelect function to receive the checkbox (this) as a parameter (I highlighted it for you with an arrow below). If the checkbox is checked, set the innerHTML values. If it's not checked, set them to an empty string:
▼
function modulecontractsSelect(checkbox) {
if (checkbox.checked) {
document.getElementById("module-contracts-summary").innerHTML = "Module contractbeheer"
document.getElementById("module-contracts-summary-price").innerHTML = "€5 / mnd";
}
else {
document.getElementById("module-contracts-summary").innerHTML = "";
document.getElementById("module-contracts-summary-price").innerHTML = "";
}
}

Change your checkbox code to something like:
<input type="checkbox" class="custom-control-input" onchange="modulecontractsSelect(this.checked)">
Then change your modulecontractsSelect function to something like:
function modulecontractsSelect(is_checked) {
if( is_checked ) {
document.getElementById("module-contracts-summary").innerHTML = "Module contractbeheer"
document.getElementById("module-contracts-summary-price").innerHTML = "€5 / mnd";
} else {
document.getElementById("module-contracts-summary").innerHTML = "";
document.getElementById("module-contracts-summary-price").innerHTML = "";
}
}
Please note I haven't tested this code, but you should get the idea.

Related

How do I retrieve values from checkboxes in JavaScript, using onchange to trigger a function?

I'm a High School student who takes a programming course (JavaScript) at school. We just had a test (which I miserably failed), but we are allowed to try again.
I have a couple of checkboxes. They all have an onchange which triggers a function later. I want to retrieve their values when I click on the checkboxes.
I've browsed around here a bit and seen something called jQuery. I have no idea what that is, so I would highly appreciate to get my help in pure JavaScript.
Okay, here is what I have of code. Note: Some variables and such are in Norwegian. I don't think it should be a problem, since I show the references to all.
My inputs (checkboxes):
<input type="checkbox" class="tur" value="0" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="1" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="2" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="3" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="4" onchange="funcSjekkBoks(this)">
I only need their value to be numbers, since I will use those in reference to an array list I have later.
Here is my function:
var inputTur = document.getElementsByClassName("tur");
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
var resultatListe = [];
if (checkboxEl.checked) {
resultatListe.push(inputTur.value);
console.log(resultatListe);
}
else {
console.log("usant")
}
}
What I would like to happen (if all checkboxes are checked from top to bottom):
resultatListe = [0, 1, 2, 3, 4]
When I uncheck a checkbox, it's value will be removed from the array.
Here is what currently happens:
When I check a checkbox I get [undefined] in my console, when I uncheck a checkbox I get usant (although that is the expected response, I haven't worked with the else part of my if-sentence yet.)
Below code will work for you:
var resultatListe = [];
function funcSjekkBoks(checkboxEl) {
var value = parseInt(checkboxEl.value);
if (checkboxEl.checked) {
resultatListe.push(value);
console.log(resultatListe);
}
else {
console.log("usant");
var indexToRemove = resultatListe.indexOf(value);
resultatListe.splice(indexToRemove,1);
}
}
You need to keep the array resultatListe outside the function other it will be initialized to empty everytime a checkbox is checked/un-checked, triggering the onchange handler. You were getting undefined as you were accessing 'value' property on HTMLCollection object which does not contain that property. Read more about it on MDN
var inputTur = document.getElementsByClassName("tur");
var resultatListe = [];
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
if (checkboxEl.checked) {
resultatListe.push(parseInt(checkboxEl.value));
}
else {
resultatListe = resultatListe.filter(d => d != checkboxEl.value)
}
console.log(resultatListe);
}
There were 2 mistakes in your logic:
1) You need to define resultatListe outside the function so that it won't get initialized to an empty array everytime
2) In you code resultatListe.push(inputTur.value); inputTur is the HTMLCollection of checkboxes whereas you need the single checkbox.
For the else logic, if the value of each checkbox is going to be unique you can use array.prototype.filter method to filter out the value of checkbox from resultatListe

Need help validating radio buttons with JavaScript

I need help validating radio buttons with JavaScript. Here's the section of HTML:
<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" /> Yes, both!<br/>
<input type="radio" name="receptionattend" value="yesc" /> Yes, but only the ceremony! <br/>
<input type="radio" name="receptionattend" value="yesr" /> Yes, but only the reception!<br/>
<input type="radio" name="receptionattend" value="no" /> No, you guys are lame!
And here's the simplest validation code I have:
function validateForm()
var y=document.forms["rsvpform"]["receptionattend"].checked;
if (y==null || y=="")
{
alert("Please indicate whether or not you will attend.");
return false;
}
}
My issue mostly seems to be that, no matter how I code the validation, it returns an error message even when I have a radio button selected.
The first issue you have is that in general, you should force a default in your radio buttons, make one of the buttons be already "checked" and you will never have a null value passed to your form checker. Most people expect their radio buttons to have a default already checked and this is standard practice in web development.
However, should you need to check for null or undefined, you should use typeof and strict comparison with ===
(typeof y === "undefined" || y === null);
After reading your comment - I noticed one other thing. Are you trying get get the value directly from Javascript by reading the DOM with like an onclick function? You won't be able to do this because you aren't ever actually getting your checked value with this line.
var y=document.forms["rsvpform"]["receptionattend"].checked;
Instead, try something like this.
var y = document.getElementsByName('receptionattend');
var y_value;
for(var i = 0; i < y.length; i++){
if(y[i].checked){
y_value = y[i].value;
}
}
y_value should now return the result of the checked radio button. If nothing was checked y_value will be null.
this line:
var y=document.forms["rsvpform"]["receptionattend"].checked;
returns either true or false based on checked attribute of your element, so you should be doing:
if ( !y ) { //if not checked i.e false
alert("Please indicate whether or not you will attend.");
return false;
}
do like:
function validateForm() {
var is_checked = false;
var eles = document.forms["rsvpform"]["receptionattend"];
for(var i = 0; i < eles.length; i++ ) {
if( eles[i].checked ) {
is_checked = true;
break;
}
}
if (!is_checked)
{
alert("Please indicate whether or not you will attend.");
return false;
}
else {
alert("valid");
}
}
Demo:: jsFiddle
I'm not going to suggest using jquery just for this. But should you end up using jquery, it makes this kind of validation very easy.
HTML Note the use of Labels, this is just a good practice, it means your uses can click on the text and a whole raft of other accesibililty bonuses.
<span class="formbold">Will you be attending the ceremony and reception?</span><br/>
<input type="radio" name="receptionattend" value="yesboth" id="rcBoth" /><label for="rcBoth">Yes, both!</label><br/>
<input type="radio" name="receptionattend" value="yesc" id="rcCOnly" /><label for="rcCOnly"> Yes, but only the ceremony! </label><br/>
<input type="radio" name="receptionattend" value="yesr" id="rcROnly" /><label for="rcROnly">Yes, but only the reception!</label><br/>
<input type="radio" name="receptionattend" value="no" id="rcNo" /><label for="rcNo"> No, you guys are lame!</label><br />
<input type="button" value="Validate Me" id="btnValidate"/>
Javascript/Jquery Wire this up in the jquery $(document).ready event.
$("#btnValidate").click(function(){
//The following selector is not very efficient, classes
//or a bounding element (eg div or fieldset) would be better
if($("input[name='receptionattend']:checked").length == 0)
{
alert("Please tell us if you're attending or not!");
}
});
http://jsfiddle.net/wpMvp/
To break down the script
$("#btnValidate").click(function(){}); adds an onlclick event handler to the button with ID btnValidate
$("input[name='receptionattend']:checked").length returns how many input elements with a name of receptionattend are checked
the rest should be fairy self explanatory

How to check if an input is a radio - javascript

How can I check if a field is a radio button?
I tried if(document.FORMNAME.FIELDNAME.type =='radio') but document.FORMNAME.FIELDNAME.type is returning undefined.
The html on the page is
<input name="FIELDNAME" type="radio" value="1" >
<input name="FIELDNAME" type="radio" value="0" >
Unless I am taking the whole approach wrong. My goal is to get the value of an input field, but sometimes that field is a radio button and sometimes its a hidden or text field.
Thanks.
Your example does not work because document.FORMNAME.FIELDNAME is actually an array with 2 elements (since you have 2 inputs with that name on the form). Writing if(document.FORMNAME.FIELDNAME[0].type =='radio') would work.
EDIT: Note that if you don't know if document.FORMNAME.FIELDNAME is a radio (ie you might have a text/textarea/other) it is a good idea to test if document.FORMNAME.FIELDNAME is an array first, then if the type of it's first element is 'radio'. Something like if((document.FORMNAME.FIELDNAME.length && document.FORMNAME.FIELDNAME[0].type =='radio') || document.FORMNAME.FIELDNAME.type =='radio')
In case you don't have a form then maybe go by attribute is an option.
var elements = document.getElementsByName('nameOfMyRadiobuttons');
elements.forEach(function (item, index) {
if (item.getAttribute("type") == 'radio') {
var message = "Found radiobutton with value " + item.value;
if(item.checked) {
message += " and it is checked!"
}
alert(message);
}
});
Your code should work, but you could try the following:
document.getElementById('idofinput').type == 'radio'
Edit: Your code doesn't work for the reason mihaimm mentions above

Javascript replace method not functioning in checkbox if/else toggle

I have a bit of Javascript I'm playing with, which is called by a number of checkboxes and will ideally perform an action (adding and removing &attributeValue=attribID to the URL cumulatively) upon the checkbox being checked/unchecked.
Here's the Javascript:
var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
var elementII = document.getElementById(attribID);
if(elementII.checked){
filterFullURL = filterFullURL+"&attributeValue="+attribID;
}
else {
filterFullURL.replace("&attributeValue="+attribID, "");
alert(filterFullURL);
}
}
So what I'm doing here is attempting to on check of a checkbox add that checkbox's attributeValue to the URL, and on uncheck of a checkbox, remove that checkbox's attributeValue from the URL. I am using the filterFullURL = filterFullURL+"..." because there are multiple checkboxes and I want all their attributeValues to cumulatively be added to the URL.
All of this is working fine - the only thing that isn't working fine is the else statement action -
filterFullURL.replace("&attributeValue="+attribID, "");
Here are some example checkboxes:
<input type="checkbox" onclick="filterToggle('price_range_0_20')" name="Price_Range" value="Below_$20" id="price_range_0_20" /> Below $20
<input type="checkbox" onclick="filterToggle('price_range_20_40')" name="Price_Range" value="$20_-_$40" id="price_range_20_40" /> $20 - $40
<input type="checkbox" onclick="filterToggle('price_range_40_70')" name="Price_Range" value="$40_-_$70" id="price_range_40_70" /> $40 - $70
So to recap - I can add the attributeValues of all the checkboxes together, but I can't delete any of them. Any help here? Thanks!
Do you not need to save the output of filterFullURL.replace like filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "")?
There was also an alert missing from the if statement - not sure if that's intentional, but this should operate well for you:
var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
var elementII = document.getElementById(attribID);
if(elementII.checked){
filterFullURL = filterFullURL+"&attributeValue="+attribID;
alert(filterFullURL);
}
else {
filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "");
alert(filterFullURL);
}
}

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources