I need checkbox selected after page reload I am trying this code.
Here my check box
<tr>
<td class="label" style="text-align:right">Company:</td>
<td class="bodyBlack">
<%=c B.getCompanyName() %>
</td>
<td>
<input type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px">> Show all paid and unpaid transactions
<br>
</td>
</tr>
//here java script code
<script type="text/javascript">
function checkBox12() {
var jagdi = document.getElementById("check").value;
if (jagdi != "") {
document.getElementById("check").checked = true;
}
console.log("jagdi is " + jagdi);
//here my url
window.location.replace("/reports/buyers/statementAccount.jsp?all=" + jagdi);
return $('#check').is(':checked');
}
</script>
Add attribute checked=checked in your html input tag:
<input checked="checked" type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px"/>
Why don't you use only jQuery ?
function checkBox12()
{
var jagdi = false;
if($("#check").length != 0) // use this if you wanted to verify if the element #check is present
jagdi = $("#check").prop("checked");
//here my url
window.location.replace("/reports/buyers/statementAccount.jsp?all="+jagdi);
}
For answer your question, you can check your checkbox when the document is ready
$(document).ready(function() {
$("check").prop("checked", true");
});
But the better way is to add checked="checked" in your HTML. The checkbox will be checked by default. /!\ input need "/" in close tag
<input type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px" checked="checked" />
It looks like you are using some other base language. I use php , and it overs POST, GET and SESSION to store values globally and for time you need.
Better find a equivalent function in your language. worth it in long term and on project expansion.
You can store state of checkbox on cookie and repopulate it after page reload.
also there is an example in here HERE!
$(":checkbox").on("change", function(){
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
});
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();
Related
I am using the following code snippet to pass parameters to URL so the specific search can be accessed via the generated link.
For example, if Potato is selected, then the URL changes to example.com#potato
However, instead of appending the URL with a hash, I want to append ?filter=
So if Potato is selected, I want the URL to change to example.com?filter=potato
How can I achieve this?
$(function() {
$(".vegetables, .seasoning").on("change", function() {
var hash = $(".vegetables:checked, .seasoning:checked").map(function() {
return this.value;
}).toArray();
hash = hash.join(",");
location.hash = hash;
});
if (location.hash !== "") {
var hash = location.hash.substr(1).split(",");
hash.forEach(function(value) {
$("input[value=" + value + "]").prop("checked", true);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h3>Filter recipes:</h3>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" class="vegetables" value="potato"> Potato</label><br>
<label><input type="checkbox" class="vegetables" value="onion"> Onion</label><br>
<label><input type="checkbox" class="vegetables" value="tomato"> Tomato</label><br>
</div>
<div>
<p>Select seasoning</p>
<label><input type="checkbox" class="seasoning" value="salt"> Salt</label><br>
<label><input type="checkbox" class="seasoning" value="pepper"> Pepper</label><br>
<label><input type="checkbox" class="seasoning" value="chilli"> Chilli Flakes</label><br>
</div>
You can use pushState() to update the current URL without reloading the page:
$(".vegetables, .seasoning").on("change", function() {
var values = $(".vegetables:checked, .seasoning:checked").map((i, el) => el.value).get();
window.history.pushState({}, '', `?filter=${values.join(',')}`);
});
I am dynamically printing out checkboxes depending on list from database, called in the code 'coachProperties'. Each coachProperty will get their own checkbox appended with the text which is unique.
I want to add this to another object 'properties'. Something like 'properties{text1 : "false, text2 : "true"} to then later on take it to server-side to do some filtering. I dont want any sumbit button since i want it to dynimcally update which i have js code for. All values in 'properties' will start with "false" which should update when checkbox is clicked. The problem is, sometimes when I uncheck a box it still displays as true and vice versa.
<div data-id="coachPropertiesCheckbox">
<% coachProperties.get('coachProperties').forEach(function (coachProperty) { %>
<div class="checkboxes">
<label>
<input type="checkbox" data-id="test" value="<%= coachProperty.text %>"> <%= coachProperty.text %>
</label>
</label>
</div>
<% }); %>
</div>
Js code:
function setProp(obj,prop,value){
obj[prop] = value;
};
var properties = {};
coachProperties.get('coachProperties').forEach(function (coachProperty) {
properties[coachProperty.text] = "false";
});
view.$el.find('[data-id="coachPropertiesCheckbox"] div.checkboxes input').change(function () {
var isCheckboxedChecked = view.$el.find('[data-id="test"]').is(':checked');
var valueCheckbox = $(this).attr("value");
setProp(properties, valueCheckbox, isCheckboxedChecked );
$.each( properties, function( key, value ) {
console.log( key + ": " + value );
});
});
Use value property to hold data that you would like to associate with the checkbox and do not use it to toggle true and false. Whether checkbox is checked or not, you can know from the checked property.
A piece of advice, most probably, you'll NOT want to use checkbox label same as value because values are for internal purpose, for any data manipulation, and labels have sole purpose of display in the UI.
Please try the following solution direction:
$('.checkboxes input').on('change', (event) => {
const checked = $(event.target).prop('checked')
const value = $(event.target).prop('value')
console.log(checked, ':', value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="checkbox1-id" value="checkbox-1" /><label for="checkbox1-id">Checkbox 1</label>
<input type="checkbox" id="checkbox2-id" value="checkbox-2" /><label for="checkbox2-id">Checkbox 2</label>
<input type="checkbox" id="checkbox3-id" value="checkbox-3" /><label for="checkbox3-id">Checkbox 3</label>
</div>
view.$el.find('div.checkboxes input').change(function (event) {
var id = $(event.target).attr('data-id');
if ($(event.target).prop('checked')) {
resultSetParameters.get('filter').coachProperties.push(id);
resultSetParameters.trigger('change');
} else {
var index = resultSetParameters.get('filter').coachProperties.indexOf(id);
if (index > -1) {
resultSetParameters.get('filter').coachProperties.splice(index, 1);
resultSetParameters.trigger('change');
}
}
});
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
I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll
I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});