how to save toggle button state on refresh using javascript - javascript

Hey everyone I am having difficulty keeping the state of my toggle button on when i refresh the page, it is stored in localStorage correctly, but even after several attempts, I wasn't able to call the function to execute on page refresh
save.addEventListener('click', () => {
localStorage.setItem("checkbox1", checkBox1.checked);
localStorage.setItem("checkbox2", checkBox2.checked);
localStorage.setItem('timezone', timezone.selectedIndex);
}
function isChecked() {
const checkBox1 = document.getElementById('checkbox1');
if (document.getElementById('checkbox1').checked == false) {
localStorage.getItem('checkbox1');
}
}
window.onload = function() {
isChecked();
};
}
<form>
<div class="toggle-switch-1">
<p class="notification-1">Send Email Notifications</p>
<!-- toggle switch goes here -->
<label type="button" class="switch-light switch-candy">
<input id="checkbox1" type="checkbox">
<span>
<span id="off">Off</span>
<!-- <span id="on1">On</span> -->
<!-- <button onclick="check()" id="on1">On</button> -->
<span id="on1">On</span>
<a></a>
</span>
</label>
</div>
<div class="toggle-switch-2">
<p class="notification-2">Send Profile to Public</p>
<!-- toggle switch goes here -->
<label class="switch-light switch-candy" onclick="">
<input id="checkbox2" type="checkbox">
<span>
<span id="off">Off</span>
<span id="on2">On</span>
<a></a>
</span>
</label>
</div>
<select class="form-field" id="timezone">
<option disabled selected>Select Timezone</option>
<option>Eastern Standard Time (EST)</option>
<option>Pacific Standard Time (PST)</option>
<option>Central Standard Time (CST)</option>
<option>Mountain Standard Time (MST)</option>
</select>
<div class="settings-button">
<button type="button" class="button-primary" id="save">Save</button>
<button class="button-disabled" id="cancel">Cancel</button>
</div>
</form>
Im trying to save the state of the button on refresh (clicking save button) but it defaults to off when I refresh as well as the drop down list of timezones, if anyone can help clear this up, I would appreciate it Thank you!!

You are just getting the value from the local storage. But not actually assigning it to any toggle buttons. You need to assign them to make it work
function isChecked() {
document.getElementById('checkbox1').checked = localStorage.getItem('checkbox1') === 'true');
}
This is how it works:
Get the value out of local storage.
The value saved in the local storage would be of type string.
So we need to convert it to Boolean value to make it work. The === check will do that for you.
Finally assign it to the checkbox.

Related

How do I make a checkbox that automatically refreshes the page without changing the values of inputs?

I'm trying to make a checkbox that will automatically refresh the page every few seconds or minutes when checked using JavaScript.
I found some ways to make it refresh the page, but when it does that, all of the inputs including the checkbox return to their default value. I want them to keep their current value when the page gets refreshed. How can I do that?
Here's the HTML code:
<section id="menu">
<div class="menu_item">
From <input type="date" name="start_date" id="start_date"> To <input type="date" id="end_date" id="end_date">
<button id="set_dates">Set dates</button>
</div>
<div class="menu_item">
<input type="checkbox" name="auto_refresh" id="auto_refresh" checked> Auto refresh
</div>
<div class="menu_item">
<input type="checkbox" name="show_desc" id="show_desc"> Show descriptions
</div>
<div class="menu_item">
Column width <input type="number" name="col_width" id="col_width" min="100" max="5000" value="100" >
</div>
</section>
I tried using this JavaScript code but it didn't work as I expected:
let checkbox = document.getElementById("auto_refresh");
function auto_refresh() {
if(checkbox.checked == true) {
let timeoutID = setTimeout("window.location.reload()", 5000);
} else {
clearTimeout(timeoutID);
}
}
if(checkbox.checked == true) {
auto_refresh();
}
checkbox.onchange = auto_refresh;
I would appreciate some help and advice.
On every input change you can call a function and set the value to browser localStorage. Then, On page start(refresh), call a function to retrieve the data back from localStorage and set the view.
To set the value, localStorage.setItem("col_width", "100");
To retrieve the value, localStorage.getItem("col_width");

Can I check the check box even if I click a button somewhere else?

I'd like to inquire.
On the page I made, products are displayed. It's not a "shop," but a page where you can inquire about the product if you have any questions while looking at it.
Click the "Inquiry" button at the top and the inquiry form will come down.
In here, all the products on the page are in a check box.
(The form is WordPress "wpforms" plug-in.)
What I want to inquire about is that can I check the check box in the "Inquiry Form" if I click a specific button such as product name while just looking at the product in the list?
Even if someone clicks the button on the product list, it will be convenient if it is checked in the check box of the inquiry form. But this is too hard for me...
url
https://thepagegallery49.cafe24.com/wp/publication/
list
<div class="news-text-box">
<span class="news-date"><?php the_sub_field('pbauthor'); ?></span>
<span class="news-title"><?php the_sub_field('pbtitle'); ?></span>
<span class="news-text"><?php the_sub_field('pbdetail'); ?></span>
<span class="checkbutton">Check</span>
</div>
checkbox
<div id="wpforms-187-field_28-container" class="wpforms-field wpforms-field-checkbox wpforms-one-third" data-field-id="28">
<label class="wpforms-field-label" for="wpforms-187-field_28">Selection</label>
<ul id="wpforms-187-field_28">
<li class="choice-1 depth-1">
<input type="checkbox" id="wpforms-187-field_28_1" name="wpforms[fields][28][]"
value="Book title 1" class="wpforms-valid" aria-invalid="false">
<label class="wpforms-field-label-inline" for="wpforms-187-field_28_1">Book title 1</label>
</li>
<li class="choice-2 depth-1 wpforms-selected">
<input type="checkbox" id="wpforms-187-field_28_2" name="wpforms[fields][28][]"
value="Book title 2" class="wpforms-valid">
<label class="wpforms-field-label-inline" for="wpforms-187-field_28_2">Book title 2</label>
</li>
...
</ul>
</div>
Yes, you can achieve this by adding eventListener to the button you wish to be clicked in order to check the checkbox, and then in the callback function of the eventListener, set the value of checkbox accordingly.
<button id="btn">hi</button>
<input type="checkbox" id="checkbox"></input>
document.getElementById("btn").addEventListener("click", () => {
document.getElementById("checkbox").checked = true;
})
and for toggling the checkbox
document.getElementById("btn").addEventListener("click", () => {
var checkbox = document.getElementById('checkbox');
checkbox.checked = !checkbox.checked;
})

How to remove multiple files uploaded from an array based on user selection in javascript or angular

Hi I need to remove multiple files uploaded from an array based on user selection in javascript or angular.........
I have tried with below code
First we have some files that are uploaded in an array and are displayed in checkboxes as shown below in code
<div *ngFor="let image of imagefilename" style="margin-left:10%">
<label class="container" style="font-size:14px">
{{image.name}} ModifiedDate:{{image.lastModifiedDate}}
<input type="checkbox" style="float:left" value="{{image.name}}" [(ngModel)]="imageChecked"
[name]="image.name">
<span class="checkmark"></span> <br><br>
</label>
</div>
<button *ngIf="imagefilename.length" class="btn btn-danger" type="submit" (click)="resetimage(imagefilename)">Reset Selected files</button>
The user will click on the checkboxes that are to be removed and then click on the button displayed and
it calls a function as displayed below
resetimage(imageName:any) {
for(var i = 0; i<this.imagefilename.length;i++){
if(this.imageChecked){
this.imagefilename.splice(i,1);
}
}
}
So in this function, only the first file in the array is removed although the user has selected multiple files to remove.
So please help me if there is any solution.
Expected result :
to remove multiple files uploaded from an array based on user selection in javascript or angular
Actual result :
Only first file is removed even though the user has selected multiple files.(as per my code)
your property imageChecked is not binded with image. You should add property imageChecked in image and modify html like below.
<div *ngFor="let image of imagefilename" style="margin-left:10%">
<label class="container" style="font-size:14px">
{{image.name}} ModifiedDate:{{image.lastModifiedDate}}
<input type="checkbox" style="float:left" value="{{image.name}}" [(ngModel)]="image.imageChecked"
[name]="image.name">
<span class="checkmark"></span> <br><br>
</label>
</div>
<button *ngIf="imagefilename.length" class="btn btn-danger" type="submit" (click)="resetimage(imagefilename)">Reset Selected files</button>
And you code should be like this
resetimage(imageName:any) {
for(var i =this.imagefilename.length;i--){
if(this.imagefilename[i].imageChecked){
this.imagefilename.splice(i,1);
}
}
}

How to change a DropDownListFor value back to null with javascript on ASP.NET - MVC?

I have multiple DropDownListFor assigned to the same variable that are hidden and only get visible when a certain radiobutton is activated with javascript. The problem is, if you change the value of a DropDownListFor and then change the radiobutton, the value for the previous DropDownListFor is still active, even tho is not visible, and when i submit, the previous DropDownListFor value is the one that gets passed.
Is there a way to bring the value of all the DropDownListFor back to the default 'null' in javascript without reloading the page?
View code:
<h3>Tipo de Infraestrutura:</h3>
<input type="radio" name="selectedLinhaType" id="150KV"/> 150kV <br>
<input type="radio" name="selectedLinhaType" id="220KV"/> 220KV <br>
<input type="radio" name="selectedLinhaType" id="400KV"/> 440KV <br>
<div class ="infobox" id="is150KV">
<fieldset>
<h3>Linha 150KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, ViewData["ListLinhas150"] as List<SelectListItem>, "")</p>
</fieldset>
</div>
<div class ="infobox" id="is220KV">
<fieldset>
<h3>Linha 220KV:</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, ViewData["ListLinhas220"] as List<SelectListItem>, "")</p>
</fieldset>
</div>
<div class="infobox" id="is400KV">
<fieldset>
<h3>Linha 400KV</h3>
<p>#Html.DropDownListFor(m => m.SelectedLinha.NumLinha, ViewData["ListLinhas400"] as List<SelectListItem>, "")</p>
</fieldset>
</div>
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$('#is150KV').hide(); $('#is220KV').hide(); $('#is400KV').hide();
$('#150KV').change(function () {
$('#is220KV').hide(); $('#is400KV').hide();
$('#is150KV').show();
});
$('#220KV').change(function () {
$('#is150KV').hide(); $('#is400KV').hide();
$('#is220KV').show();
});
$('#400KV').change(function () {
$('#is150KV').hide(); $('#is220KV').hide();
$('#is400KV').show();
});
})
</script>
Edit:
Fixed, added ids to each DropDownListFor and disabled/enabled it on javascript with '.attr'. '.prop' should work too but i didn't test it.
Thanks for the help.
Instead of simply hiding the drop down list, disable it. Disabled form elements are not submitted ever.
$('#is220KV').attr('disabled', true).hide();
And conversely:
$('#is220KV').attr('disabled', false).show();

jQuery/JS - Hiding specific dynamically created elements/buttons

I've built a simple chat application with message rating functionality. I want to prevent self-ratings by hiding the corresponding rating buttons. So on Bob's screen for example there should be no rating buttons next to Bob's messages.
I've tried to realize that by comparing the #name and #user-name. If they are equal, the rating buttons should be hidden. But it looks like I'm doing that not correctly.
That main problem is that a message div .standard-msg is created dynamically so I need something like "on-dom-change".
Every help appriciated.
$("#standard-msg").on("DOMSubtreeModified", function() {
$('.standard-msg').each(function() {
if ($('#name').val() == $(this).find('#user-name').text()) {
$('button').hide();
}
});
});
<div id="chat-wrapper" class="wrapper">
<div class="message-box" id="message-box">
<div class="standard-msg">
<button class="rating like-btn">Like</button>
<button class="rating dislike-btn">Dislike</button><span style="color:#FF7000" class="user-name">Bob</span> : <span class="user-message">hi</span>
</div>
<div class="standard-msg">
<button class="rating like-btn">Like</button>
<button class="rating dislike-btn">Dislike</button><span style="color:#FF7000" class="user-name">Alice</span> : <span class="user-message">hello</span>
</div>
</div>
<div class="panel">
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="10" />
<input type="text" name="message" id="message" placeholder="Message" maxlength="80" />
<button id="send-btn" class="btn">Send</button>
</div>
</div>
If the buttons were added to the page after the page has loaded then they won't respond to any code (in the page before they were created) that references them. This is because new event listeners are added for the buttons when they are created and somehow they don't pickup on any code older than they are.
To get around this quirk, just add the code dynamically as you add the buttons to the page and it should work.
e.g.
var s = "$('#standard-msg').on('DOMSubtreeModified', function() { $('.standard-msg').each(function() { if ($('#name').val() == $(this).find('#user-name').text()) { $('button').hide(); } }); }); ";
then append to the page,
$("body").append(s);

Categories

Resources