After reload the page checkbox should not reset - javascript

I am using Angular-Js and Jquery. I am implementing disable all checkboxes in the page after click on checkbox. But When I reload the page my page is reset, I don't want to reset disable checkboxes after reload. Suppose I checked checkbox after that reload the page checkbox should be checked.
Below is the code example.
$('#mainChk').on('click', function(){
var categories = $('.disableCheck');
categories.prop('disabled', !categories.prop('disabled'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="mainChk" type="checkbox" > Main
<input type="checkbox" class="disableCheck"> First
<input type="checkbox" class="disableCheck"> Second
<input type="checkbox" class="disableCheck"> Third
When I reload the page, All checkbox is reset.
I can use Angular-Js also. I set checkbox value in query parameter like true or false.
$location.search({ checkbox: disableCheck.prop('disabled') })
But I did not get desired output.

You can use something like sessionStorage or localStorage to save checkboxes' state after page reloading.
There is an angularjs library, that I use.
You also can find same thing for jQuery.

The best way is to call ajax on page load via API method though SELECT query of Save Table.
<input type="checkbox" class="disableCheck" value="First"> First
<input type="checkbox" class="disableCheck" value="Second"> Second
<input type="checkbox" class="disableCheck" value="Third"> Third
$(document).ready(function () {
$.ajax({
url: 'abc.asmx',// Call List Method of Save Checkbox Table
success: function (data) {
callback(data);
},
})
});
function callback(data) {
$.each(data.d, function (index, item) {
$("#checkboxId option[value='" + item.SaveCheckboxColumnName + "']").prop("checked",
true);
$("#checkboxId option[value='" + item.SaveCheckboxColumnName +
"']").prop("disabled",
true);
});
}

Related

Trigger click once when page is loaded

I have a form in my page like so:
<form id="shipping" action="some-action-url" method="post">
<ul>
<li>
<input id="ship238280" name="method" value="238280|479435" type="radio" checked="checked">
<label for="ship238280">Transport (€0,00)</label>
</li>
<li>
<input id="ship292259" name="method" value="292259|580109" type="radio">
<label for="ship292259">Pick up (€0,00)</label>
</li>
</ul>
</form>
I'm using a SaaS platform so I have limited access to scripts and need to make use of what's actually available. So I'm looking for more of a workaround....
In above form I have checked the first option. To actually set the first shipping option I have to submit the form. Then in the system this option is set.
So I have a function that submits the form:
function sendform(){
var loader = $('.cart-loader');
var form = $('#shipping');
$(loader).show()
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(data) {
$(loader).hide()
//$(this).unbind()
}
});
}
And a click event for when I click one of the options:
$('#shipping input').on('click', function(){
sendform()
});
What I want now is to submit the form on page load. So I have created something like this:
$(function(){
$('#shipping input').each(function(){
if($(this).is(':checked')){
$(this).trigger('click') // or sendform()
}
});
});
What happens now is that the form keeps submitting because everytime the page reloads (after submit) it wants to submit again!
How can I work around this knowing that it needs to submit first to set the option?
I tried things like $(document).one('ready', function(){ or something like $(this).unbind() in ajax success function.
I'm a bit lost :) So any help greatly appreciated!!
Try something like this: https://jsfiddle.net/noidee/uvm6jw3b/
$(document).ready(function(){
if( localStorage.getItem('submited') !== '1' ){
$('#myform').submit();
localStorage.setItem('submited', '1');
}
});

how to pass the list of radio buttons name to spring controller and show them to the success page

I have a list of radio buttons while selecting
I am facing one issue with below code as i am getting only value of first radio button in my js function for others (i mean other than first radio) it is giving null. PFB code
<tr> <td> <input type="radio" id="selectedTempList" name="template" value="${templateList.finalTemplateName}" onclick="getSelectedTempName()"></td> <td><c:out value="${templateList.finalTemplateName}"></c:out></td></tr>
My java script function
$("#selectedTempList").each(function() {
if($(this).is(':checked'))
selectedTemplateName=$(this).val();
});
alert("radio select values"+selectedTemplateName);
}
var radioValueArrya = [];
$("#r1").each(function() {
if($(this).is(':checked'))
radio1=$(this).val();
radioValueArrya.push(radio1);
alert("radio select values"+radio1);
});
$("#r2").each(function() {
if($(this).is(':checked'))
radio2=$(this).val();
radioValueArrya.push(radio2);
alert("radio select values"+radio2);
});
// controller call
$("#divid").load("${contextPath}/actionName?kRadio="+escape(radio1) +"" +
"&sRadio="
+"" +escape(radio2)+"&radioValueArrya="+radioValueArrya);
And in your JSP file use <input type="hidden" id="radioValueArrya" name="radioValueArrya"/>
And in your Controller add parameter #RequestParam List<String> radioValueArrya in your method

Detect in Javascript which form has been submitted

I have a rating system for a bunch of entries on a website, they are programatically placed in and therefore I have given them a unique form identifier by using a count.
<form name="star">
<input type="radio" class="star" name="rating" id ="rating" value="Terribad"/>
<input type="radio" class="star" name="rating" id ="rating" value="Meh"/>
<input type="radio" class="star" name="rating" id ="rating" value="OK"/>
<input type="radio" class="star" name="rating" id ="rating" value="Pretty Good"/>
<input type="radio" class="star" name="rating" id ="rating" value="Awesome!"/>
<input type='hidden' name='item' id = 'item' value='<%out.print(item);%>'>
</form>
<span id = "msg<%out.print(item);%>" style = "float:right; margin-left:0px; padding-top:0px;"></span>
I also have another hidden field which is the users name here (retrieved in the javascript) but removed it because its large and from a complex session based array.
I've also added the count in a hidden field to help try and sort it out.
From there I'm running a javascript on the click of one of the radio buttons that will grab some more details from the session, and do an AJAX database update.
$(function() {
$(".star").click(function() {
var submission = document.getElementsByName("rating");
var name = $("input#name").val();
var item = $("input#item").val();
var rating;
for (i = 0; i< submission.length; i++) {
if (submission[i].checked) {
rating = submission[i].value;
}
}
var submitted = 'name='+name + 'rating=' + rating;
//alert (item);return false;
$.ajax ({
type: "POST",
url: "/process_rating.jsp",
data: submitted,
success: function () {
$('#msg'+item).html("Submitted");
}
});
return false;
});
});
This all works fine on the first entry (when I didn't have that count in) but as I am not surprised all the other entries are being treated as the first. The main issue is when I try and update the msg div with its success it only does the first one as it is grabbing the hidden value from the first form, not the form that was actually submitted.
This is all inside a jsp btw.
First of all, each id should be unique on the page and you shouldn't need any of the ids in your example. This could very well be the root of many issues on your page.
Your code can be simplified quite a bit and you can use the "form" property on an input element to find the associated form. Does this work better for you?
$(function() {
$(".star").click(function() {
$.ajax ({
type: "POST",
url: "/process_rating.jsp",
data: {
name: this.form.name,
rating: $(this).val()
},
success: function () {
// Not sure what you're trying to do here... Update some input
// that you didn't show in your code?
$('#msg').html("Submitted");
}
});
return false;
});
});
I wasn't sure what you were trying to do upon successfully saving the form. Let me know and we'll see if we can get it working.
Use the "this" from the event handler function to look for the form which is the parent.
$(".star").click(function(){
var formThatWasSubmitted = $(this).parents("form")
});
Pretty sure that's how it works.

Modal box + checkbox + cookie

I would like to achieve the following:
On homepage load, display modal box
Within modal box, display a form with a single mandatory checkbox
On checking the checkbox, hit submit and close the modal box, proceed to homepage
Remember this checkbox tick preference using a cookie
On a users return to the homepage, if they have checked the checkbox,
the modal box won't display
I've been getting somewhere with this:
http://dev.iceburg.net/jquery/jqModal
In that I can get the modal box displaying on page load, but I can't work out how to get the form to make the checkbox mandatory and close the box. I also don't know where to start when setting a cookie.
Any pointers would be much appreciated.
Thanks
EDIT: to include code:
Index.html - to display modal box on page load
$().ready(function() {
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
setTimeout($('#ex2').jqmShow(),2000);
});
2.html - modal box content loaded via ajax
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
<form action="" method="POST" onSubmit="return validate(form);" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
Load the jquery cookie plugin to allow to set/read cookies: http://plugins.jquery.com/project/cookie
then.. something like this below. Untested, but you get the idea
index.html:
$().ready(function() {
if (!$.cookie('agreed_to_terms'))
{
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
$('#ex2').jqmShow();
}
});
2.html:
$().ready(function()
{
$('#agreeFrm').submit(function(e)
{
e.preventDefault();
if ($(this).find('input[name=checkbox]').is(':checked'))
{
$.cookie('agreed_to_terms', '1', { path: '/', expires: 999999 });
$('#ex2').jqmHide();
}
});
});
<form id="agreeFrm" action="" method="POST" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
I used a JQuery plugin not long ago called SimpleModal
I was very impressed with how easy it was. On the modal I had multiple checkboxes and to carried the values of the checkboxes back to the page the modal was on after a submit button was hit.
All the info and demos are on the SimpleModal homepage
It works, finally!
I was missing the callback when the cookie exists and these tics '' around the value of the cookie.
Here is how it looks like. Please, let me know if there is some obvious mistake.
(many thanks for your support)
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'Proceed'){
$.cookie("agreed_to_terms", '1', { expires : 1, path: '/' }); //set cookie, expires in 365 days
(typeof callback == 'string') ?
window.location.href = callback :
callback();
}
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: 'true', trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
if ($.cookie('agreed_to_terms') == '1'){window.location.href = callback =
callback()
//they already have cookie set
}else{
confirm('About to visit: '+this.href+' !',this.href);
}
return false;
});
});// JavaScript Document

Change button behaviour if checkbox is checked

I have a checkbox which functions as a toggle and when clicked submits a form with the check / unchecked status being used to enable / disable the service.
However, I now have an API which selects preferences based on location and I want to:
Click submit if the checkbox is unchecked
Click apply if the checkbox is checked
Currently I have $(“#checkbox”).click(); if the user calls the API and I’m not sure how to implement this where $(“#apply”).click(); would be used if the checkbox was checked already to avoid turning the service off. I've tried $('#checkbox').attr but not having problems with it.
$(‘#apicall’).off('click').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'json',
url: "https:// [PRIVATE API REDACTED]“,
success : function(result){
console.log(result);
result=result.successData.server;
best_ovpn=best_ovpn.trim();
$(“#dropdown”).val(apical);
show_openvpn_status();
if($('#checkbox').attr('checked')) {
$(" # checkbox ").click();
} else {
$(" # apply ").click();
}
});
});
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if(this.checked){
alert("Checkbox is checked.");
}
else if(!(this.checked)){
alert("Checkbox is unchecked.");
}
});
});
You can use this code to check whether a checkbox is checked or not. You can make appropriate api calls based on its status.
$('#checkbox').on('change', function(){
if($(this).is(':checked')){
alert('checked');
}else{
alert('unchecked');
}
});
if you want to know if the checkbox is checked, you can use .is method of jQuery along with :checked like this:
$(function(){
console.log("Checkbox1", $("#checkbox1").is(":checked"));
console.log("Checkbox2", $("#checkbox2").is(":checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="checkbox1" type="checkbox" checked />
<input id="checkbox2" type="checkbox" />
and when you want to check the checkbox you can use .prop method :
$(function(){
$('#checkbox').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox" />
<p>Checked the checkbox using jQuery</p>

Categories

Resources