remember checkbox and radio button state after page reload - javascript

I am making a filter with jQuery and Laravel (PHP). It filters the data when I click the checkbox or radio button but, if I click checkbox or radio button and refresh the page the state of checked checkbox or radio button will no longer remain. I want the checked state to remain even after the page reloads.
This is my code.
<div class="search">
<input type="radio" name="expertise[]" value="backend" />programmer
<input type="radio" name="expertise[]" value="frontend" />programmer
</div>
<div class="avail">
<p>
<input type="checkbox" name="available[]" value="20" />20
</p>
<p>
<input type="checkbox" name="available[]" value="30" />30
</p>
</div>
jQuery
<script>
var expertise = [];
var available = [];
$(document).on('change', 'input[name="expertise[]"], input[name="available[]"]', function(e) {
e.preventDefault();
types = [];
available = [];
if (document.location.href.indexOf('filter') > -1) {
var url = '../developers/filter?type=dev';
} else {
var url = '/developers/filter?type=dev';
}
$('input[name="type[]"]:checked').each(function() {
expertise.push($(this).val());
url = url + '&expertise=' + $(this).val();
});
$('input[name="available[]"]:checked').each(function() {
available.push($(this).val());
url = url + '&available=' + $(this).val();
});
if (document.location.href.indexOf('filter') > -1) {
$.get('../developers/filter', {
type: 'dev',
expertise: expertise,
available: available,
}, function(markup) {
$('.dev-holder').html(markup);
});
} else {
$.get('developers/filter', {
type: 'dev',
expertise: expertise,
available: available,
}, function(markup) {
$('.dev-holder').html(markup);
});
}
window.history.pushState("", "", url);
});
</script>
Laravel controller
public function search(Request $request)
{
$type = $request->get('expertise');
$availability = $request->get('available');
$url = 'filter';
$users = User::where('type','dev')->where('is_approved', '=', 1);
if (!empty($type)) {
$users = $users->where('expertise','dev');
}
$users->when($availability, function ($query, $availability ) {
return $query->where(function ($whereQuery) use ($availability ) {
foreach ($availability as $item) {
$whereQuery->orWhere('avaibility', 'LIKE', $item);
}
});
});

You are already pushing things to the URL so when you load the page you can check the url query string for what's set or not.
$(function () {
var urlSearchParams = new URLSearchParams(window.location.search);
if (urlSearchParams.get('expertise[]')) {
$('input[name="expertise[]"][value="'+urlSearchParams.get('expertise[]')+'"]').prop('checked', true);
}
urlSearchParams.getAll('available[]').forEach(function (val) {
$('input[name="available[]"][value="'+val+'"]').prop('checked', true);
});
});
Note that the URLSearchParams needs to be polyfilled in IE
This can also be achieved via the HTML and Laravel:
<div class="expertise">
<input type="radio" name="expertise[]" id="backend" value="backend"
{{in_array('backend', request()->input('expertise',[])) ? 'checked' : ''}} />Backend
<input type="radio" name="expertise[]" id="frontend" value="frontend"
{{in_array('frontend', request()->input('expertise',[])) ? 'checked' : ''}}/>Frontend
</div>
<div class="availability">
<p>
<input type="checkbox" name="available[]" value="above30"
{{in_array('above30', request()->input('available',[])) ? 'checked' : ''}}
/>Above 30 hrs/week
</p>
<p>
<input type="checkbox" name="available[]" value="below30"
{{in_array('below30', request()->input('available',[])) ? 'checked' : ''}}
/>Below 30 hrs/week
</p>
</div>
This is assuming you have this HTML in a .blade.php file

U can use local storage for saving the state. Suppose if check box is clicked then store it in local storage and if page reloads make a function to extract data from the local storage and apply it.

JS/jQuery: Save into localStorage
PHP/Laravel: Save in session,
session_start();
if (!isset($_SESSION['vals']) {
$_SESSION['vals'] = 'default=stuff'
}
$_SESSION['vals'] //access it like this
and then you can change it when they submit
,
//set
let values = ["yes"]
localStorage.setItem('vals',JSON.stringify(values))
//retrieve
let result = localStorage.getItem('vals')
result = JSON.parse(result)
//use
if (result[0] = "yes") {
yourradiothing.checked = true
}
You can also store other things.

Related

clicking through saved checkbox states

The below works to save the states of my checkboxes, then sets the items saved back to checked when called in my load__() function; however I need to instead of just setting to checked, I need to actually have them .click() through in my load__() function as the data is not being served otherwise.
function checkSaver() {
user = JSON.parse(localStorage.getItem(user));
var inputs = document.querySelectorAll('input[type="checkbox"]');
user.userAchkData = [];
inputs.forEach(function(input){
user.userAchkData.push({ id: input.id, checked: input.checked });
});
localStorage.setItem(username, JSON.stringify(user));
console.log(JSON.stringify(user));
}
function load_() {
// get saved latest checkbox states, recheck
user = JSON.parse(localStorage.getItem(user));
var inputs = user.userAchkData;
inputs.forEach(function(input){
if (input.id) {
// I need to click through the found checked here
document.getElementById(input.id).checked = input.checked;
}
});
You can check if they're checked and then programmatically trigger a click:
if (input.id) {
// I need to click through the found checked here
const element = document.getElementById(input.id);
element.checked = input.checked;
if (input.checked) element.click();
}
I fiddled around a bit and got to a simple working example for checking saved checkboxes. Maybe you can adapt this to your needs:
const container = document.getElementById('checkboxes');
const data = JSON.parse(localStorage.getItem('checkboxes')) || new Array(3).fill(false);
window.addEventListener('DOMContentLoaded', () => {
[...container.children].forEach((child, i) => { child.checked = data[i]; });
});
container.onchange = ({ target }) => {
data[target.dataset.id] = target.checked;
localStorage.setItem('checkboxes', JSON.stringify(data));
};
<div id="checkboxes">
<input type="checkbox" data-id="0">
<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
</div>

Best way to append querystring to url when a checkbox is selected while saving checkbox state?

I am making a checklist form and currently i am able to append the value of the selected boxes to the url in I feel an inefficient way and the main issue is that the state of the checkbox doesnt save either so a user cant see what they checked or uncheck.
This is the html code
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()">
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()">
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()">
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()">
</form>
This is the script to make the url
let form = document.getElementById("carForm")
let checkboxes = document.getElementsByTagName("input")
var vals = "";
let formSubmit = () => {
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals = checkboxes[i].value
// append checkbox values to url
var url = window.location.href;
if (url.indexOf('?') > -1){
// if a paramter already exists, append using
url += `&make=${vals}`
}else{
url += `?make=${vals}`
}
window.location.href = url;
}
console.log(vals);
}
}
function checkboxChanged() {
formSubmit()
}
</script>
So for instance if kia and honda were selected the url would be
/inventory?make=kia&make=honda
So if this is inefficient whats a better way of doing this and how do i ensure the checkbox state is persisted after the page is reloaded I am using nodejs/expressjs on server side and ejs
var makes=[];
...
for (var i=0;i<checkboxes.length;i++) {
if (checkboxes[i].checked) makes.push(checkboxes[i].value);
}
...
url+='&makes='+makes.join(',');
This will give you a comma delimited list; you can string split it on the server side.
You should take a look at URLSearchParams. Using it, you could do something like this:
const searchParams = new URLSearchParams(location.search);
document.querySelector('input[type=checkbox]').forEach(cb => {
if (cb.checked) {
searchParams.append('make', cb.value)
}
});
location.href = location.href.replace(location.search, '?' + searchParams.toString())
I think that you should not define all the parametres of the url as make=..., but with ${vals}=checked. Then you can read it easily with php and just check the names that are defined, but you will have to define a name for your chackboxes.
Sorry for my approximative english, I am swiss and speak french.
If you have access to a server-side language, like PHP, use that to check the URL and auto-check the boxes when the page loads. Something along these lines:
<?php
$bools = [
"kia" => isset($_GET['kia']),
"bmw" => isset($_GET['bmw']),
"mercedes" => isset($_GET['mercedes']),
"toyota" => isset($_GET['toyota'])
];
?>
<form id="carForm" method="get">
<label>BMW</label>
<input type="checkbox" value="bmw" onChange="checkboxChanged()" <?= $bools['bmw'] ? 'checked' : '' ?>>
<label>mercedes</label>
<input type="checkbox" value="mercedes" onChange="checkboxChanged()" <?= $bools['mercedes'] ? 'checked' : '' ?>>
<label>honda</label>
<input type="checkbox" value="honda" onChange="checkboxChanged()" <?= $bools['honda'] ? 'checked' : '' ?>>
<label>toyota</label>
<input type="checkbox" value="toyota" onChange="checkboxChanged()" <?= $bools['toyota'] ? 'checked' : '' ?>>
</form>
Protip: In PHP, you can use value="car[]" in order to submit an array of values which will already be an array type in PHP!
If you don't have access to server-side, or you don't wish to use it, then check the URL on page-load:
window.onload = () => {
for (const el of checkboxes) {
// Check the URL's params:
// From link below
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get(el.value);
if (myParam != null) {
el.checked = true;
}
}
}
(Get URL params reference, there are more options with better support than what I used. I just used the simplest option)

How do I keep single checkbox stay checked after refreshing the page?

HTML code:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
This will make the checkbox stays checked, but when page is refresh or exit and comes back, the checkbox will be unchecked. Therefore, after some research, I tried the localStorage, but doesn't seem to quite figure it out yet.
localStorage code:
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
I have script tags around the localStorage code and after implementing these codes, my checkbox still doesn't stays checked.
Both code as a whole:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" name="new_background"/>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
</script>
<input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>
I would like to thank everyone that took time to help me figure out the solution to my question with the biggest thanks to #Pranav C Balan!!! Check out the finished code # http://stackoverflow.com/a/44321072/3037257
I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.
One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
</div>
Working demo : FIDDLE
<script>
// document ready handler
// or $(document).ready(Function(){...
jQuery(function($) {
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
});
</script>
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
Working demo : FIDDLE
An alternative to localStorage that only utilizes document.cookie:
$('input:checkbox').change(function() {
saveCookies();
});
To register the function and the actual function:
function saveCookies() {
var checkArray = [];
$('input.comic-check').each(function() {
if ($(this).is(':checked')) {
checkArray.push(1);
} else {
checkArray.push(0);
}
});
document.cookie = "checks=" + checkArray;
}
This is an alternative to localStorage, and depends on whether you want it to persist longer
And to retrieve the saved (on load)
var checks = getCookie("checks");
if (checks != "") {
checkArray = checks.split(',');
//unchecks boxes based on cookies
//also has backwards compatability provided we only append to the list in landing.ejs/generator.js
for (var i = 0; i < checkArray.length; i++) {
if (checkArray[i] == "0" && $('input.comic-check').length > i) {
var checkBox = $('input.comic-check')[i];
$(checkBox).prop('checked', false);
}
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Three situations you will need to check the checkbox
PHP have it set to checked="checked" (checked)
localStorage have it as true (checked)
all other situations this should be unchecked
all you need is to make sure first two situation you check the checkbox, then by default it is unchecked, but in your each you are also uncheck checkbox, therefore ignored the PHP part (as php set it to checked but localStorege set it to unchecked)
Example here: https://jsfiddle.net/dalinhuang/efwc7ejb/
//on page load
$.each(checkboxValue, function(key, value) {
if(value){
$("#" + key).prop('checked', value);
}
});
I would change:
<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>
for:
<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>
In inline HTML, you don't need the checked attribute to be checked=checked.
Just checked is enought.
checked=checked is used in JavaScript to programatically check a checkbox.
EDIT
About your localStorage...
I made an example for you on CodePen
//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
$("#" + key).prop('checked', value);
});
// ================ Saving checks
// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");
// On change handler.
allCheckboxes.on("change", function() {
// Check how many checkboxes we have.
var jsonCheckboxes = {};
console.log("There is "+allCheckboxes.length+" checkboxes.");
// Building the json.
for(i=0;i<allCheckboxes.length;i++){
console.log(allCheckboxes.eq(i).attr("id"));
console.log(allCheckboxes.eq(i).is(":checked"));
jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
}
console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));
// Setting localStorage.
localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});
Working around your comment : my goal is to find something that will make my checkbox stays checked if the user choose to, here's a way to have the localStorage handle it :
jQuery (3.2.1)
$(document).ready(function() {
var bground = localStorage.getItem('background'); // get the value if exists
if (bground == 'shadow') { // checkbox has been previously checked
$('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
$('#checker').attr('');
}
$('#submit').submit(function() { // when form is submitted
bground = localStorage.getItem('background'); // get the value in LS
if($('#checker').is(':checked')) // is it checked or not ?
{ sh = 'shadow'; } else { sh = 'shadowless'; }
localStorage.setItem('background', sh); // update LS with new value
});
});
HTML (added id="submit" to form)
<form action="" id="submit" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
This will make the checkbox stays checked, and when page is refreshed, the checkbox will be checked/unchecked depending on user's previous choice.
You could also use the jQuery change function instead of form submitting.
Just modify the line :
$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line

JS check if checkbox is checked keep initial value

I have a form to update personal data with multiple checkboxes who can be initially checked or not.
<form method="post" id="up_mission">
<input checked type="checkbox" id="first">
<input type="checkbox" id="second">
<button class="btn btn-default" type="submit" id="update_mission<?php echo $id_mission ?>"</button>
</form>
and the JS:
$(function() {
$("form[id^='up_mission']").submit(function() {
var value1 = document.getElementById("first").checked;
var value2 = document.getElementById("second").checked;
$.post("update_mission.php", {value1: value1, value2:value2}, functon(data) { console.log(data) });
});
});
In update_mission.php there is a simple SQL query to update with news values and I also do var_dump($_POST); and the values printed for first and second are always the ones that I initially put in the <input> it doesn't matters if I uncheck or check the checkbox.
How can I fix it please?
Here is the part of the php file :
var_dump($_POST);
$first = $_POST['value1'];
$second = $_POST['value2'];
if ($first == "true") { $first = "on";}
else {$first = "0";}
if ($second == "true") { $second = "on";}
else {$second = "0";}
update_miss = "UPDATE table SET First = 'first', Second = 'second'[...] WHERE my_condition";
// I connect to my DB, and do the query, and there is no problem here
// I also have text input in my form and they update pretty well
Use $('#first').is(':checked') and $('#second').is(':checked') to detect state of checkbox.
$(function() {
$("form[id^='up_mission']").submit(function() {
var value1 = $('#first').is(':checked') ? 1 : 0;
var value2 = $('#second').is(':checked') ? 1 : 0;
$.post("update_mission.php", {value1: value1, value2: value2}, functon(data) { console.log(data) });
});
});

React js Execute function on submit

I have a simple search box on my react app. The box should let the user input a phrase, and then execute another react.js function when they hit the enter key. I have tried every combination (put box in a form, not in a form, onSubmit, etc), but I can't seem to stop the page from "reloading" when the user inputs the information and presses enter.
HTML:
<input className="input" placeholder="Type it Here..." type="text" name="key" id="searchgrid" />
React JS Code:
searchForMatches(){
var value = document.getElementById("searchgrid").value;
console.log(value);
}
I just need the searchForMatches() function to run when the user types the enter key into the search box.
Thanks.
EDIT
Yes, you get the key pressed with onKeyPress event in element
Check the snippet
var Comp = React.createClass({
searchForMatches(e) {
var value = String.fromCharCode(e.charCode)
this.setState({
keyPressed: value
})
},
getInitialState() {
return ({
keyPressed: ''
})
},
render() {
return ( < div >
< label > Last Key Pressed: {
this.state.keyPressed
} < /label><br / >
< input className = "input"
placeholder = "Type it Here..."
type = "text"
name = "key"
id = "searchgrid"
onKeyPress = {
this.searchForMatches
}
/>
</div >
)
}
})
ReactDOM.render( < Comp / > , document.getElementById('foo'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='foo'></div>
Check the system events on React JS (https://facebook.github.io/react/docs/events.html)
For Search Options you can do the following :
HTML :
<div class="pull-right" style='display:block;'>
<span style="color:red"><strong>Search Products</strong></span>
<form method="get">
<input name="keysearch" value="" placeholder="name" id="keysearch" type="text" class="form-control">
<span id="loading"></span>
</form>
<div id="result"></div>
</div>
SCRIPT USED :
<script>
$(document).ready(function(){
var req = null;
$('#keysearch').on('keyup', function(){
var key = $('#keysearch').val();
if (key && key.length > 0){
$('#loading').css('display', 'block');
if (req)
req.abort();
req = $.ajax({
url : 'fetch_records.php',
type : 'GET',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
$('#loading').css('display', 'none');
$("#result").html(data).show();
$("#result").css('position', 'absolute');
$("#result").css('z-index', '1');
// style='display:block; position :absolute; z-index:1'
}
}
});
}
else
{
$('#loading').css('display', 'none');
$('#result').css('display', 'none');
}
});
});
</script>
PHP fetch-records.php File:
<?php
$conn = mysqli_connect('localhost','root', '','Name_OF_DB');
if(isset($_GET['keysearch']))
{
$search = $_GET['keysearch'];
$search = mysqli_real_escape_string($conn,$search);
// $data = "SELECT * FROM products ";
$data = "SELECT * FROM products WHERE product_title LIKE '%{$search}%' order by product_id ";
// $query = query ("SELECT * FROM products WHERE product_category_id = ".$id." ORDER BY product_price DESC");
$result = mysqli_query($conn,$data);
if (mysqli_num_rows($result)>0)
{
while($row= mysqli_fetch_assoc($result))
{
echo"<a href='create_a_new_page_brother.php?id={$row['product_id']}&price=0' class='list-group-item'>{$row['product_title']}</a>";
}
}
}
?>

Categories

Resources