Remember if checkbox checked across multiple html files - javascript

I have a checkbox in each page of my website that toggles dark mode, but if it is checked (dark mode enabled) and I change pages, the page defaults to lite mode. I was wondering if it would be possible to set it up so that it will remember if the checkbox was checked and automatically check it on the new page, it would also be nice to have it remember so if you close the site and reopen it it well be on the mode you selected previously but that is not 100% necessary
<!-- checkbox -->
<input type="checkbox" id="toggle">
<label for="toggle" class="togglebtn">
<i id="toggle-img" class="fa-solid fa-moon"></i>
</label>

this code:
function getFromStorage() {
document.querySelector('#toggle').checked = localStorage.getItem('dark-mode') === 'true'
}
document.querySelector("#toggle").addEventListener("change", ({ target }) => {
localStorage.setItem('dark-mode', JSON.stringify(target.checked))
})
window.addEventListener("storage", getFromStorage)
getFromStorage()

Related

Show/Hide a button if a custum field is display

I'm having a problem in a checkout page of my website (wordpress based).
I have two kind of products and for each one, during checkout, I created custom fields to collect specific informations. With conditional rules (by plugin) some fields show up only if a list of specific option is checked.
When they are hidden, analysing the code, I've this situation:
<div class="form-row form-row-wide thwcfe-html-field-wrapper thwcfe-conditional-field" id="stud_no_req_field" data-name="stud_no_req" data-rules="[[[[{"operand_type":"field","value":"2","operator":"value_eq","operand":["student"]}]]]]" data-rules-action="show" style="display: none;">...</div>
When they are showing up, style attribute change in "block".
At the end of the page, I also have a button to submit the order.
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Associati" data-value="Associati">Associati</button>
I'm looking for a script that hides this button if custom file above has "display:block" and viceversa (show button if div has "display:none").
I've tried with this script (in checkout page), but nothing happens:
<script>
$(document).ready(function() {
if ($("#stud_no_req_field").style.display == "block")
{
$("#place_order").style.display = "none";
}
else
{
$("#place_order").style.display = "block";
}
});
</script>
I also need that this script is automatic (no click needed) and listens to any automatic change of div style (inside html tag).
Thank you very much!!! You are my angels!
You're using the wrong code. You should do
$("#place_order")[0].style.display = 'none'; // I added [0]
Or use jQuery API (https://api.jquery.com/css/)
$("#place_order").css('display', 'none');

Materialize CSS - passing data to sideNav

I'm using materializeCss for my latest project and I have a problem.
I use sideNav to open a 'modal' inside of which is a contact form.
This contact form should be used in multiple occasions and different informations should be prefilled depending on which button does user click.
Let me explain it in an example:
If user clicks on Send Message then the forms input title should be something like
<input type='text' id='title' name='title' readonly value="General message">
and if user clicks on button Request Candy then this input should be something like
<input type='text' id='title' name='title' readonly value="I want candies!">
Since the sideNav opens by clicking on an element of type
<i class="material-icons">menu</i>
I had an idea to react on the click as
$(document).on('click', '.button-collapse', function() {
console.log('got it!');
$('#title').val('My custom message from data-* or something..');
})
but this doesn't work since probably materialize hijacks click events on these a.button-collapse's. I don't even get the console log got it!.
Does anybody know a way to pass some data to the newly open sideNav?
UPDATE:
jsfiddle
<input> is a "head only" tag - has no closing </input> and yet element has no content.
So you markup shall look like
<input type='text' id='title' name='title' value='General message' readonly></input>
UPDATE:
Change to this:
$('.button-collapse').on('click', function() {
$('#title').val($(this).data('title'));
console.log('I have been clicked');
})
and it will work. Seems like document or framework is consuming the event so you cannot handle it on that level.
Theres a bug in your event handler, this will work.
$('.button-collapse').sideNav({
menuWidth: 200, // Default is 240
edge: 'right', // Choose the horizontal origin
//closeOnClick: true, // Closes side-nav on <a> clicks, useful for Angular/Meteor
//draggable: true // Choose whether you can drag to open on touch screens
});
$(".button-collapse").click((e) => {
$('#title').val($(e.target).data('title'));
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/js/materialize.min.js"></script>
<ul id="slide-out" class="side-nav">
<input type="text" id="title" name="title" value="my Title">
</ul>
Option 1
Option 2

How do I make this Javascript checkbox trigger action work like my CSS only example

I'm using the following code to test for "if" a checkbox is checked on page load.
If it is, then a certain additional field will be shown (called myfield):
<style>
#myfield {
display: none;
}
</style>
<input type="checkbox" id="mycheckbox" name="mycheckbox" />
<input type='text' id='myfield' name='myfield' />
<script>
if ($("#mycheckbox").is(":checked")) {
document.getElementById("id").style.display="block";
}
</script>
However, this only works when the page loads and the checkbox is already checked. It doesn't work live when the box isn't checked on page load, and you go to click the box. I want the hidden field to show up right away when the box is "checked" without the page having to reload. I then want myfield to hide right away when the box is unchecked.
Can any anyone point out the better/proper way to do this?
Additionally:
Of note: I do know how to do this in CSS using labels, but I need to use javascript other times.
Here's what works fine in modern browsers using just CSS: http://jsfiddle.net/3KTC3/
Here's that CSS only jsfiddle code:
<style type="text/css">
.label-for-check {
display:none;
}
.check-with-label:checked + .label-for-check {
display:block;
}
</style>
<div>
<input type="checkbox" id="check" class="check-with-label" />
<label for="check" class="label-for-check">
<br /><br />MyField<br />
<input type='text' id='myfield' name='myfield' size='10' />
</label>
<div>
You need to attach a change event handler. Your posted code only executes when page is loaded, it doesn't watch over your element's state.
Here's a jQuery equivalent to your CSS version with classes and adjacent selector:
$('.check-with-label').change(function() {
$(this).next().toggle(this.checked);
}).change();
Fiddle
Explanation: this references the checkbox being clicked, get the next element (equivalent to your CSS + selector) and toggle its display based on the checked state of the checkbox.
Another version that works only with your 2 given IDs:
$('#mycheckbox').change(function() {
$('#myfield').toggle(this.checked);
}).change();
Fiddle
Note that your CSS version is compatible with all desktop browsers including IE7 and above. Consider whether it is necessary to use JS for this.
edit: You have to trigger the change handler after attaching it, so if the checkbox is already checked when the page is loaded, the triggered handler will display the field.
Your problem is that jQuery will only check one time (when you load the site) if your checkbox is checked.
The change handler will fire every time the user changes the checkbox, if it is cheked it will show #myfield
Do something like this:
$('#mycheckbox').change(function() {
if ($(this).is(":checked")) {
$('#myfield').show()
}
});
$(document).ready(function(){
if($("#mycheckbox").is(":checked")) $('#myfield').show();
$('#mycheckbox').on('change', function(){
if($(this).is(":checked")) {
$('#myfield').show();
} else {
$('#myfield').hide();
}
})
});

Opt-in / Opt-out Checkbox

I am trying to create a simple way to force a single checkbox to display "No" in a form submission if left unchecked, or clicked off. I've tried a number of ways and this is the closest I can get, but it still isn't working properly.
Any help is much appreciated.
Matt
$(function opt() {
if ($("#optIn").is(":checked")) {
$("#optIn").value="Yes"
$("#optIn").click(function() { this.value="No" })
} else {
$("#optIn").value="No"
$("#optIn").click(function() { this.value="Yes" })
}
return false
});
opt();
An unchecked checked box is not a successful control and is therefore not POSTed with the rest of the form data.
The easiest solution for this is to create a hidden input with the same name as your checkbox that will contain the "unchecked" value:
<input type="hidden" name="myCheckbox" value="No" />
<input type="checkbox" name="myCheckbox" value="Yes" />
This will cause the form to POST myCheckbox=No if the checkbox is left unchecked.
So to start out quite frankly, I'm not sure where you saw that sort of function setup before. You're code, as-is, could be reduced to this:
$(function() { // on DOM ready (when the DOM is finished loading)
$('#optIn').click(function() { // when the checkbox is clicked
var checked = $('#optIn').is(':checked'); // check the state
$('#optIn').val(checked ? "Yes" : "No"); // set the value
});
$('#optIn').triggerHandler("click"); // initialize the value
});
The value of the checkbox, however, is never displayed on the screen. You may need to update a separate field with the values "Yes" or "No", such as:
<input type="checkbox" id="optIn" />
<span id="optInLabel"/>No</span>
And the script:
$(function() { // on DOM ready (when the DOM is finished loading)
$('#optIn').click(function() {
optIn(this);
});
optIn($('#optIn')[0]);
});
function optIn(el) {
var checked = $(el).is(':checked'); // check the state
$('#optInLabel').html(checked ? "Yes" : "No"); // set the value
}
EDIT: Working jsFiddle
If you need to check whether the box is checked on the server-side post-form-submission, then you could also update a hidden input field with the value "Yes" or "No" and ignore the submitted checkbox element value (as jaredhoyt mentioned in his answer).
Use radio buttons:
<span>Opt in?</span>
<br>
<input type="radio" name="optIn" value="no" checked>No
<input type="radio" name="optIn" value="yes">Yes
No javascript required, works in every browser, no shims, no libraries, nothing.

JQuery Custom Image From Checkbox to Radio

I am using the following code to make a custom checkbox with my own images and it works but it's using a Checkbox and I need to use Radio buttons.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#moreinfo").change(function() {
if(this.checked) {
$(this).prev().attr("src", "checkbox_unchecked.gif");
} else {
$(this).prev().attr("src", "checkbox_checked.gif");
}
});
});
</script>
Next...here's the HTML:
<label for="moreinfo">
<img src="checkbox_unchecked.gif"/>
<input name="moreinfo" type="checkbox" id="moreinfo" style="display:none">
</label>
If it a question of changing from checkbox to radio type or does the jquery need changing too?
How do I go about this?
Change the type="checkbox" to type="radio" (and add some more radio buttons for testing, grouping them via the name attribute, they may not have the same id as IDs are unique!). Then, you also need to handle the click event of the replacement images.
But actually, that's going beyond your original question, which you could have solved by simply trying it out. ;)
A Radio Button uses also the attribute checked. So you can switch the element without changing the script (perhaps the gifs).
But your script will never run, because your checkbox/radio button is not displayed.
So you need some functionality to change the status when clicking the image.

Categories

Resources