Remember checkbox value - html

Hi I would be so grateful if anyone could shed some light on this, Basically I have a iphone app built using jqtouch and phonegap which has a list of standard checkboxes and when they are selected a strikethrough effect will be applied, easy enough (kind of like a simple checklist) this is all dealt with on the client side and nothing will be getting sent anywhere.
However, when the user closes the app the checkboxes revert to their original sate i.e all unchecked and i would like them remain as the user left them. I guess local storage would be the way to do this, however, i have gave it a go and i am getting a bit confused.
Any help would be great, and thank you in advance.
kyle

Here you go:
$(document).ready(function() {
$('form')
.delegate(':checkbox','change',function() {
var $this = $(this);
localStorage.setItem('checkbox' + $this.index('form :checkbox'),$this.attr('checked').toString());
})
.find(':checkbox')
.each(function(index) {
if(localStorage.getItem('checkbox' + index) === 'true') $(this).attr('checked',true);
});
});
Took some time to write it correctly myself but I think it's worth it. The default state handling is up to you (like when a checkbox is already checked with HTML).

Related

Jquery Game-loop Selection Drop-down

Please help, how would you make a timer that runs some code for a time specifed by the user selecting an option from a dropdown menu ? Jquery please.
PS: I tried to attach my code but I'm getting errors (here on the stacks)
Please help, any ideas welcome. I'm really struggling
First of all, to set a "timer" in js in general, you use
setTimeout(() => some_stuff, time_in_ms)
for example, to send a console.log in half a second, you'll use
setTimeout(() => {console.log("hi");}, 500);
So, when the user selects the option from the dropdown menu, just start a timer with the delay as what the user chose, and the function as whatever you want to run.
If you don't already have a dropdown menu, this tutorial might come in handy to create it: https://www.w3schools.com/howto/howto_js_dropdown.asp
But yea, as the comment mentioned, please also send your code, because without it its really hard to give accurate help.

How would I go about using a text-box to complete a URL and then open said URL in a new tab?

I'm looking to make a simple HTML site that redirects to another URL. I want the input inside the textbox to 'complete' a URL, and then open said completed URL. However I've not found any way to do such a thing, and I'm rather new to coding in general so I turned to here in the last attempt.
I want the user to be able to input something (say they input "abcxyz"), and when they click a button or press enter, they are redirected to something like 'genericsite.com/[input]' (in this case, genericsite.com/abcxyz).
I assume I'll have to use some JS for this, but I have almost zero knowledge on JS so I was having trouble finding any topic on this. Any help would be appreciated.
Ended up finding an old snippet of code from a few years back that worked for me
{
var name = document.getElementById('myName').value;
var url = 'http://www.genericsite.com/' + encodeURIComponent(name);
// In current window
window.location.href = url;
// In new window
window.open(url);
}

How can I disable a button when I press another button

I am a beginner in app scripting and I have a question.
How can I disable a button when I press another button.
I tried many different ways, but I can't get it to work.
Can you help me?
My code is large. Should I paste it here?
in UiApp you can use clientHandler to do that very easily...
example code goes like this :
function doGet() {
var app = UiApp.createApplication();
var btn1 = app.createButton('button1');
var btn2 = app.createButton('button2');
var clientHandler = app.createClientHandler().forTargets(btn1).setEnabled(false);
btn2.addClickHandler(clientHandler);
return app.add(btn1).add(btn2);
}
Note : the comments above are right... your question was indeed too vague.
Yes, you will need to post some relevant code before anyone will be able to help you.
Broadly speaking, a good logical approach to achieving what you want to do, is to use the event that occurs, or state that is invoked by clicking the first button, to run script that will disable your second button.
This can be done many different ways. Client Side, Server Side.. it all really depends on context as to which is right for your situation.

Clear all fields in a form upon going back with browser back button

I need a way to clear all the fields within a form when a user uses the browser back button. Right now, the browser remembers all the last values and displays them when you go back.
More clarification on why I need this
I've a disabled input field whose value is auto-generated using an algorithm to make it unique within a certain group of data. Once I've submitted the form and data is entered into the database, user should not be able to use the same value again to submit the same form. Hence I've disabled the input field in the first place. But if the user uses the browser back button, the browser remembers the last value and the same value is retained in the input field. Hence the user can submit the form with the same value again.
What I don't understand is what exactly happens when you press the browser back button. It seem like the entire page is retrieved from cache without ever contacting the server if the page size is within the browser cache limit. How do I ensure that the page is loaded from the server regardless of browser setting when you press the browser back button?
Another way without JavaScript is to use <form autocomplete="off"> to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:
window.addEventListener("pageshow", () => {
// update hidden input field
});
See more details for Gecko and WebKit implementations.
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset to do any good.
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
This is what worked for me.
$(window).bind("pageshow", function() {
$("#id").val('');
$("#another_id").val('');
});
I initially had this in the $(document).ready section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.
Because I have some complicated forms with some fields that are pre-fill by JS, clearing all fields is not suitable for me. So I found this solution, it detects the page was accessed by hitting the back/forward button and then does a page reload to get everything back to its original state. I think it will be useful to someone:
window.onpageshow = function(event) {
if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
location.reload();
}
};
As indicated in other answers setting autocomplete to "off" does the trick, but in php, what worked for me looks like this...
$form['select_state'] = array(
'#type' => 'select',
'#attributes' => array('autocomplete' =>'off'),
'#options' => $options_state,
'#default_value' => 'none');

How can you check to see if someone has modified your HTML (using something like Firebug)?

Is there an easy way to check to see if someone has modified your HTML? I am currently writing some code that takes data from the DOM and submits it to the backend where it will of course be sanitized and checked for accuracy, but I was wondering if there was a way to kind of head that off at the pass.
For instance, if I have a hidden input with a number in it and someone modifies that number in Firebug before submitting it to my server, is there a way to check to see if the actual HTML was modified before submitting the request to the server and basically telling them HEY BUDDY STOP MESSING WITH MY STUFF.
I'm not entirely sure this is possible, but if it is, I do not know how to do it.
Hmm, I'd say that the HTML on your users' browser is actually theirs. (i.e. nothing wrong with greasemonkey) Stuff isn't yours again until it arrives at your server in the form of the URL, HTML form input parameters, and cookies -- all of which can of course be modified unbenknownst to you. So you should continue to validate such data; there's no magic bullet to allow for a trusted client experience.
You could send along with your hidden value another value that is the result of a complex computation you performed involving the hidden value and some secret value that never gets sent to the client. Then when you receive the hidden value simply perform another calculation that reverses the first one. If you don't get your secret value back then you know they have changed the hidden value.
Of course, this is still not going to be that secure as someone can easily do some experiments on your site and find out what that secret value is based solely off of your hidden value and verification value and then change the verification value as well.
It is possible to come up with a computation that will make it rather difficult (but not impossible) to crack this type of verification. However, with the time and effort that would be involved in coming up with such a computation and then staying on top of it to ensure no new exploits come out for it, you would probably be better off just sanitizing the data as you receive it.
In my opinion you are better off not relying on any data received by the user. There are certainly tricks that can be done to do what you ask and this may be one of them but most all of these tricks are ones that can most likely be figured out by an attacker given enough time.
You could see if somebody is changing hidden input elements with Firebug using JavaScript, but the idea sounds silly.
All your critical validation should be done server-side.
You can't rely on anything the client sends being accurate. If somebody really wanted to "mess with your stuff", they could easily (for example) write a Python script to submit data to your server.
Here's a jQuery-based sample of what I was alluding to in my comment:
Live Demo #2
Click Submit: the background will turn green - nothing was changed.
Change the value of a hidden input, click Submit: the background will turn red - something was changed.
HTML:
<form id="myForm" method="post" action="">
<input type="hidden" value="123" />
<input type="hidden" value="456" />
<input type="submit" />
</form>
JS #2:
$('#myForm input[type="hidden"]').each(function() {
$(this).data('originalValue', $(this).val());
});
$('#myForm').submit(function(){
$(this).find('input[type="hidden"]').each(function() {
if ($(this).val() != $(this).data('originalValue')) {
$('body').css('background', 'red');
return false;
}
//just for testing:
$('body').css('background', 'green');
});
return false;
});
There are things you can do in JavaScript, like keeping a copy of the expected value buried in JavaScript:
var originalHiddenFieldValue = document.getElementById("myHiddenField").value;
... later...
if (originalHiddenFieldValue !== document.getElementById("myHiddenField").value)
alert("Hey, stop it!");
At the end of the day though, all the user would have to do is detach any event handlers on your submit button to override any validation and your code would be useless. If they're smart enough to be overriding values using Firebug, you can make a good bet that they'd be willing to go a bit further to modify your scripts too.
If you're trying to check for these things, the only way you can do it with 100% confidence is to check the hidden field server-side, and compare the values, as you have said you are doing anyway.