Javascript function does not work on onclick of checkbox - javascript

I try to call a Javascript function through an onclick attribute of a checkbox.
The js should show another checkbox if the first one is checked etc.
Now the function isnt working. I tried to use just an alert() for testing without any result...
Fitness:<input type="checkbox" id="fitnessCheck" onclick="checkFunction()">
Beauty:<input type="checkbox" id="beautyCheck">
Streetwear:<input type="checkbox" id="streetwearCheck">
Luxus:<input type="checkbox" id="luxusCheck" onClick="checkFunction()">
Datenschutz: <input style="display:none" type="checkbox" id="datenschutzCheck">
<script>
checkFunction(){
//get Checkboxes
var fitnessCheckbox = document.getElementById("fitnessCheck");
var beautyCheckbox = document.getElementById("beautyCheck");
var streetwearCheckbox = document.getElementById("streetwearCheck");
var luxusCheckbox = document.getElementById("luxusCheck");
var datenschutzCheckbox = document.getElementById("datenschutzCheck");
if(fitnessCheckbox.checked == true || beautyCheckbox.checked == true || streetwearCheckbox.checked == true || luxusCheckbox.checked == true){
datenschutzCheckbox.style.display ="block";
}
}</script>

You have to declare the function checkFunction().
You can do it in many ways such as:
function checkFunction() {
// code here
}
or
var checkFunction = function() {
// code here
}
etc, depending on how you are going to use the function.

This is how to define a function in JavaScript.
Correct your function as below;
function checkFunction(){
}
Alternatively, remove the onclick attribute from HTML and put it in the JavaScript as defined below
var fitnessCheckbox = document.getElementById("fitnessCheck");
fitnessCheckbox.onclick() = function() {
// access properties using this keyword
if ( this.checked ) {
// if checked ...
alert( this.value );
} else {
// if not checked ...
}

Related

Store multiple checkbox inputs in local storage

I have multiple checkbox inputs that look like this:
<input type="checkbox" id="box-1">
<input type="checkbox" id="box-2">
<input type="checkbox" id="box-3">
I want to store their values (checked or unchecked) in the browser's local store.
The javascript that I'm using to do this is:
function onClickBox() {
let checked = $("#box-1").is(":checked");
let checked = $("#box-2").is(":checked");
let checked = $("#box-3").is(":checked");
localStorage.setItem("checked", checked);
}
function onReady() {
let checked = "true" == localStorage.getItem("checked");
$("#box-1").prop('checked', checked);
$("#box-2").prop('checked', checked);
$("#box-3").prop('checked', checked);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
The first part saves the checkbox's state on the click and the second part loads it when the page refreshes.
This works well if the lines for box 2 and 3 are removed, but I need it to work with all the checkboxes.
Your main issue here is that you're only storing a single value in localStorage, checked, which will be overwritten every time you check a different box. You instead need to store the state of all boxes. An array is ideal for this, however localStorage can only hold strings, so you will need to serialise/deserialise the data when you attempt to read or save it.
You can also simplify the logic which retrieves the values of the boxes by putting a common class on them and using map() to build the aforementioned array. Try this:
<input type="checkbox" id="box-1" class="box" />
<input type="checkbox" id="box-2" class="box" />
<input type="checkbox" id="box-3" class="box" />
jQuery($ => {
var arr = JSON.parse(localStorage.getItem('checked')) || [];
arr.forEach((c, i) => $('.box').eq(i).prop('checked', c));
$(".box").click(() => {
var arr = $('.box').map((i, el) => el.checked).get();
localStorage.setItem("checked", JSON.stringify(arr));
});
});
Working example
function onClickBox() {
let checked1 = $("#box-1").is(":checked");
let checked2 = $("#box-2").is(":checked");
let checked3 = $("#box-3").is(":checked");
localStorage.setItem("checked1", checked1);
localStorage.setItem("checked2", checked2);
localStorage.setItem("checked3", checked3);
}
function onReady() {
let checked1 = "true" == localStorage.getItem("checked1");
let checked2 = "true" == localStorage.getItem("checked2");
let checked3 = "true" == localStorage.getItem("checked3");
$("#box-1").prop('checked', checked1);
$("#box-2").prop('checked', checked2);
$("#box-3").prop('checked', checked3);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
Of course you could simplify it further by doing
function onClickBox(boxNumber) {
let checked = $("#box-" + boxNumber).is(":checked");
localStorage.setItem("checked" + boxNumber, checked);
}
function onReady() {
[1, 2, 3].forEach( function(boxNumber) {
$("#box-" + boxNumber).prop(
'checked',
localStorage.getItem("checked" + boxNumber)
);
$("#box-" + boxNumber).click( function() {
localStorage.setItem(
"checked" + boxNumber,
$("#box-" + boxNumber).is(":checked")
);
});
})
}
$(document).ready(onReady);
Your check variable is getting overwritten, you can put it inside for loop.
So your code becomes,
function onClickBox() {
for(var i=1;i<=3;i++){
let checked=$("#box-"+i).is(":checked");
localStorage.setItem("checked-"+i, checked);
}
}
function onReady() {
for(var i=1;i<=3;i++){
if(localStorage.getItem("checked-"+i)=="true"){
var checked=true;
}
else{
var checked=false;
}
$("#box-"+i).prop('checked', checked);
onClickBox();
}
}
$(document).ready(onReady);
Please follow the below Code (Very Simple Javascript works)
<input type="checkbox" id="box">checkbox</input>
<button type="button" onClick="save()">save</button>
<script>
function save() {
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked;
</script>
with simple modification, you can use it without save button..
Hope this Helps you..

How to take an input that is equal to 10 and perform a function that says awesome to the screen

I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}

Add another condition to Show/Hide Divs

I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.

LocalStorage with Userscript on Chrome

I badly need someway to store data within an edited DOM of a page, and then access it from the userscript. Also, I need this to be done on Google Chrome.
This is my current script, but I can't get it working:
The internal script:
var o_shout_tabs=unsafeWindow.localStorage.getItem('va_shout_tabs')||true;
var o_profile_damage=unsafeWindow.localStorage.getItem('va_profile_damage')||true;
var o_allies=unsafeWindow.localStorage.getItem('va_allies')||true;
The edited DOM:
<script type="text/javascript">
function saveData(a,b){
var unsafeWindow=this['unsafeWindow']||window;
unsafeWindow.localStorage.setItem('va_'+a,b);
}
</script>
<input type="checkbox" value="1" onclick="saveData('shout_tabs', this.checked)"/>
<input type="checkbox" value="1" onclick="saveData('profile_damage', this.checked)"/>
<input type="checkbox" value="1" onclick="saveData('allies', this.checked)"/>
However, this always returns false when I test with for example o_shout_tabs==true, no matter the input (although, if it hasn't received an input at all, it returns true).
What always returns false?
Anyway, the init logic is off. For boolean values, code like this:
var o_shout_tabs=unsafeWindow.localStorage.getItem('va_shout_tabs')||true;
will always return true or a string.
Use this code:
function getBoolFromStorageDefaultTrue (varName) {
var val = localStorage.getItem (varName);
if (val == null)
return true;
return ( (val == "false") ? false : true );
}
var o_shout_tabs = getBoolFromStorageDefaultTrue ('va_shout_tabs');
var o_profile_damage = getBoolFromStorageDefaultTrue ('va_profile_damage');
var o_allies = getBoolFromStorageDefaultTrue ('va_allies');

change text of corresponding label when checkbox is checked/unchecked

I can't get this javascript function to work. Any help would be much appreciated!
<input type="checkbox" class="checkit" name="smoking" id="smoking" value="1" onclick="yesno('smoking','yesnos');" /><label for="smoking" name="yesnos" id="yesnos">No</label>
function yesno(thecheckbox, thelabel){
var checkboxvar = document.getElementById(thecheckbox);
var labelvar = document.getElementById(thelabel);
if (checkboxvar.checked == false){
document.getElementById(labelvar).innerHTML = "No";
}
else{
document.getElementById(labelvar).innerHTML = "Yes";
}
}
I changed your code to this and it seems to work:
function yesno(thecheckbox, thelabel) {
var checkboxvar = document.getElementById(thecheckbox);
var labelvar = document.getElementById(thelabel);
if (!checkboxvar.checked) {
labelvar.innerHTML = "No";
}
else {
labelvar.innerHTML = "Yes";
}
}
See here on jsFiddle
You can also make it shorter and more readable like so:
<input type="checkbox" class="checkit"
name="smoking" id="smoking" value="1" onclick="yesno(this, 'yesnos');" />
<label for="smoking" name="yesnos" id="yesnos">No</label>
function yesno(chk, label) {
document.getElementById(label).innerHTML = chk.checked ? "Yes" : "No";
}
As i would use it now a day!
document.querySelectorAll('input[type="checkbox"]').forEach(function(checkbox) {
checkbox.addEventListener('change', function (event) {
let checkboxLabel = document.querySelector('label[for="'+checkbox.name+'"]');
if (checkboxLabel) checkboxLabel.textContent = checkbox.checked?"ON":"OFF";
});
});
<input type="checkbox" name="myCheckbox">
<label for="myCheckbox">OFF</label>
getElementById takes a string, not an Element. I'm assuming you're passing strings to the yesno function...
One problem is that document.getElementById() should take in thelabel, NOT labelvar.
Also, make sure your checkbox and "label" (whatever HTML element it is) have an id="" attribute.
The problem is caused by passing labelvar to document.getElementById. You've already retrieved a reference to the element by setting var labelvar = document.getElementById so your if statement can be changed to
if (checkboxvar.checked == false){
labelvar.innerHTML = "No";
}
else{
labelvar.innerHTML = "Yes";
}
I've made a pure JS version in jsfiddle here: http://jsfiddle.net/Zikes/wpwEW/
If you're using a framework like jQuery I can make that look a bit cleaner. Otherwise you'll need to modify it to use attachEvent if available for IE's sake.
You were close but you are calling getElementById() on an element that you already have..
Try this
function yesno(thecheckbox, thelabel){
var checkboxvar = document.getElementById(thecheckbox);
var labelvar = document.getElementById(thelabel);
if (checkboxvar.checked == false){
labelvar.innerHTML = "No";
}
else{
labelvar.innerHTML = "Yes";
}
}
Working example: http://jsfiddle.net/QmkDB/

Categories

Resources