localStorage : store checkboxes automatically checked - javascript

I have something like this in php:
if(isset($_POST['submit']){
$check = in_array($row['service_object_id'], $values) ? 'checked' : '';
}
echo '<input type="checkbox" class="faChkRnd" id="'.$row['service_object_id'].'" name="list[]" value="'.$row['service_object_id'].'" '.$check.'>';
Each time I press a submit button, it will check the checkboxes with values inside $check.
It's working good but I want to store the checkboxes checked in localStorage automatically after pressing the button.
I already use this script to store them after click, but it won't work automatically :
<script type = "text/javascript">
$('.faChkRnd').on('click', function() {
var fav, favs = [];
$('.faChkRnd').each(function() { // run through each of the checkboxes
fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
favs.push(fav);
});
localStorage.setItem("favorites", JSON.stringify(favs));
});
$(document).ready(function() {
var favorites = JSON.parse(localStorage.getItem('favorites'));
if (!favorites.length) {return};
console.debug(favorites);
for (var i=0; i<favorites.length; i++) {
console.debug(favorites[i].value == 'on');
$('#' + favorites[i].id ).prop('checked', favorites[i].value);
}
});
</script>
Any ideas ? Thank you !

you shound check type of favorites[i].value. string or boolean !?
string :
if(favorites[i].value == "true") {
$('#' + favorites[i].id ).prop('checked',true);
}
boolean :
$('#' + favorites[i].id ).prop('checked',favorites[i].value);
example :
string : https://jsfiddle.net/utm4za2p/1/
boolean : https://jsfiddle.net/utm4za2p/3/

You can use submit method.
You have a form with the submit button and you have to change it to just a regular button.
And you should put
$('.yourForm').submit()
to the end of click handler where you save the values to the localStorage.
Because when you press the submit button it may triggered before your click handler.
You need save values first and then submit form.

Related

Cannot uncheck checkbox

I am trying to uncheck a checkbox once my form is submitted
on the html side I have the following
<form class="form contact-form" id="contact_form">
<input type="checkbox" id="store_pickup" name="pickup" value="pickup" onclick="storeDetails()">
<label for="store_pickup">Store Pickup</label>
....
And then I have an existing JS file for the form which work for all other input types but Checkbox
$(document).ready(function(){
$("#submit_btn").click(function(){
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_name == "") {
$('input[name=name]').css('border-color', '#e41919');
proceed = false;
}
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
if (user_message == "") {
$('textarea[name=message]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userMessage': user_message
};
//Ajax post data to server
$.post('contact_business.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
}
else {
output = '<div class="success">' + response.text + '</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
// $('#store_pickup').attr('checked', false);
// $("#store_pickup").prop('checked', false);
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
// $("#store_pickup").attr('checked', false);
// $("#store_pickup").prop('checked', false);
$("#result").slideUp();
});
});
I've tried the two following statment commented out in the code but these do not work, can anyone assist me. Thank you!
You can toggle the checked attr of a HTML input of type="checkbox" with
$( elem ).prop('checked', false);
$( elem ).prop('checked', true);
You can check the current state of the checked property of the checkbox with
$( elem ).prop('checked')
You can also use Chrome Inspect tool to view/test the current properties of a DOM element by selecting the element and then viewing the 'properties' tab.
https://developers.google.com/web/tools/chrome-devtools/inspect-styles/edit-dom
Note: In my version of Chrome I have to deselect and then re-select the DOM element to see the properties refresh after modifying a property value with the above JS.
It's the presence of absence of a checked attribute that controls whether the checkbox is checked. Setting the value of the attribute has no effect.
So you need
$("#store_pickup").removeAttr('checked');

Radio button check and uncheck onclick and send data

I'm trying to send data onclick via ajax with a radio button. If the radio button is clicked and checked, value of 1 is set in the database. If the radio button is already checked, but clicked to uncheck it, the value of 0 is sent to the database. The code I'm using sends the value onclick and checks the radio button but does not uncheck and hence does not send the value to the database. Please help.
<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'">
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var checked = $(this).prop('checked');
if (checked != 'checked') {
$(this).prop('checked', true);
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:"1",id:id,},
});
} else if (checked == 'checked') {
$(this).prop('checked', false);
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:"0",id:id,},
});
}
});
});
</script>
A checkbox and
$('input[type="checkbox"]').on("click", function(){
$.post("updateaddress.php",{home:this.checked,id:this.id});
});
is all you need
If you MUST use a radio, have a look at this
How to Check/Uncheck single radio button
$('input[type="radio"]').on("click", function(){
$.post("updateaddress.php",{home:this.checked,id:this.id});
this.checked=!this.checked;
});
Radio buttons are used when there is multiple options and user should check only one option.so,user can't uncheck a radio button when already checked.you explicitly make a onclick listener and change the radio button status.but it's not advisable.you can use checkbox for this purpose with onchange event.
$(checkEle).on("change",function(){
var status = $(this).prop("checked");
sendStatus(status);
}
<input type="radio" name="home['. $row["id"].']" id="'. $row["id"].'">
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var data = {home:"0",id:$(this).attr("id")};
if ($(this).is(":checked")) {
data = {home:"1",id:$(this).attr("id")};
}
$.ajax({
url:"updateaddress.php",
method:"POST",
data:data,
});
});
});
</script>
You can use this script.Just check if radio button is checked or not and send your values accordingly.

How to keep the radio button remain checked after the refresh

I've read few similar questions like mine and I've tried some of the option but still did not work for my code.
Basically I have radio button where I checked it by value=\"$Id\".
The reason why it refresh to the same page is because I want it to pass new total price once the user choose their address (* the shipping fee determined by the state).
echo "<input type=\"radio\" name=\"select\" value=\"$Id\" id=\"$State\" onclick=\"test()\" > <label>$Name</label><br>";
<script>
function test(){
//got few lines of codes here
var tprice = document.getElementById("prices");
var user = document.getElementById("userid");
var b = document.querySelector('input[name="select"]:checked').value;
var tot= parseFloat(calc)+0;
var totals = parseFloat(calc) + parseFloat(tprice.value);
var userid = user.value;
window.location.href = "summary.php?tot=" + tot +"&totals="+ totals +"&userid="+ userid+"&idd="+b;
document.getElementById(b).checked = true;
</script>
you can set values in session storage on select of radio. add onclick="handleClick(this);" inside radio button.
function handleClick(myRadio) {
sessionStorage.setItem("data",JSON.stringify({"myRadioButtonId":"checked"}));
}
Now get data from local storage on document ready . And set checked attributes to that radio button.
var data = sessionStorage.getItem('data');
if(JSON.parse(data).myRadioButtonId == 'checked'){
document.getElementById("myRadioButtonId").checked = true;
}
If you want a radio button to be checked, you give it the attribute checked.
echo "<input type=\"radio\" " . $_GET['idd'] == $ID ? 'checked' : '' . " name=\"select\" value=\"$Id\" id=\"$State\" onclick=\"test()\" > <label>$Name</label><br>";
You can use localstorage or sessionstorage, cookies, or best option use php server session $_SESSION
surround your echo as form and submit onclick
<form id="myForm" method="post" action="summary.php">
echo "<input type=\"radio\" name=\"select\" value=\"$Id\" id=\"$State\" onclick=\"test()\" > <label>$Name</label><br>";
</form>
test() {
// assign to value to hidden inputs
//then submit the form
document.getElementById("myForm").submit();
}

Get / catch a button value before sending form, for form confirmation

I just want to ask the user to confirm their choice before sending a form. So I need the text value (by that I mean the innerHTML, not the value="" attribute) they have just selected/clicked for them to confirm.
The form consists of many buttons with the same name but different values (dynamically generated), so I need to "catch" it once it has been selected.
The html looks like this:
<form id="myForm" method="post" action="here.php">
<button class="bc" value="v1">foo</button>
<button class="bc" value="v2">bar</button>
</form>
I have this piece of code so far but I can't figure out how to get the value, to add it to the confirm box.
$('form#valueSelect').submit(function( event ) {
var sel = this;
var c = confirm("You have selected " + sel + " Click OK to continue?");
return c;
});
I get [object HTMLFormElement] instead of the value. I tired var sel = this.value; and value() and val and val() but it doesn't work, I don't know why.
Try to have global variable and then update it when button click. You will have then recent button clicked value in it.
var btnText = '';
$(document).ready(function(){
$('form#valueSelect').submit(function( event ) {
var c = confirm("You have selected " + btnText + " Click OK to continue?");
return c;
});
$("input[name='YourBtnName']").on("click",function(){
btnText = $(this).val();
});
});
Sorry my question wasn't quite clear.
I wanted the displayed value (innerHTML) of the button the user clicked (out of many other buttons), the html looks like this:
<form id="myForm" method="post" action="here.php">
<button class="bc" value="v1">foo</button>
<button class="bc" value="v2">bar</button>
</form>
I found a workaround by using the click instead of the submit:
$('button.bc').click(function( event ) {
var myForm = $('#myForm');
event.preventDefault();
var bval = this.value;
var choice = this.innerHTML;
var c = confirm("You have selected " + choice + "\nClick OK to continue?");
if(c == true) {
var input = $("<input>").attr("type", "hidden").attr("name", "token").val(bval);
$('#myForm').append($(input));
$('#myForm').submit();
}
});
and adding <input type="hidden" name="token"></input> in my form, in order to "store" the value of the clicked button.

cant get radio button onchange to work in cakephp

I dont get any output for my onchange event for a radio button.
I want to select 3 out of 4 a radio buttons and disable a text input field and the other enables the text input.
Currently I cant get it to output anything.
echo $this->Form->input('startDate',array('id'=>'startdatebox','label' => 'Start Date','class'=>'datepicker', 'type'=>'text','style'=>'width:100px;height:30px','value' => $datestart));
..
echo $this -> Form -> input('dateRange',
array('id'=>'dateRange2','label' => '<h6>Date Range</h6>','type' => 'radio',
'value' =>$dateSelect,'name'=>'dateRange2' ,'options' => $selectoption))
;
<script type="text/javascript">
$("input[name='data[User][dateRange2]']").on("click",function() {
$('#startdatebox, #enddatebox').prop('disabled', $(this).val() != 3);
alert( 'aasda');
});
First call onclick on your radio button, as like
echo $this -> Form -> input('dateRange',
array('id'=>'dateRange2',
'label' => '<h6>Date Range</h6>',
'type' => 'radio',
'value' =>$dateSelect,
'name'=>'dateRange2' ,
'options' => $selectoption,
'onclick'=> 'myFunc(this.value)'
)
);
Then Add javascript
<script type="text/javascript">
function myFunc(val) {
if(val != 3) {
document.getElementById("startdatebox").disabled = true;
document.getElementById("enddatebox").disabled = true;
} else {
document.getElementById("startdatebox").disabled = false;
document.getElementById("enddatebox").disabled = false;
}
}
</script>
Or, to change the disabled property of input fields using jQuery 1.6 +
function myFunc(val) {
$('#startdatebox, #enddatebox').prop('disabled', $(this).val() != 3);
}
I hope you may help it.
onChange() is not working for radio button, but it works for checkbox or select.
In order to detect the select action for radios, you have to use onclick() function instead. As Supravat's answer, you need to pass "this.value" in the onclick() function, and you get the selected value in javascript.

Categories

Resources