I’m new to jquery, but I’m trying to use it to create a multi-step tabbed form.
One one of the pages, I have radio buttons that will show several fields depending on the choice that’s selected.
The problem I find is that if the user refreshes the page after selecting a radio button, the page reloads and hides all the divs, but it remembers the selected radio button choice.
Is there a way to initially hide the divs without explicitly telling it to happen after a page loads? Perhaps some (easy) way of having jquery remember what div is hidden and which is shown?
Thanks!
<label for="paymentmethod">Payment Method</label>
<input type="radio" name="paymentmethod" id="paymentmethod" value="creditcard">Visa/Mastercard
<input type="radio" name="paymentmethod" id="paymentmethod" value="cheque">Cheque
<div id="divcredit">
Stuff
</div>
<div id="divcheque">
Stuff
</div>
Here’s the jquery code I have:
$(document).ready(function() {
//...stuff
$("#divcredit").hide();
$("#divcheque").hide();
$("input[name='paymentmethod']").change(function() {
if( $("input[name='paymentmethod']:checked").val() == "cheque")
{
$("#divcredit").hide();
$("#divcheque").show();
}
else if($("input[name='paymentmethod']:checked").val()== "creditcard")
{
$("#divcredit").show();
$("#divcheque").hide();
}
});
and add
class="payment"to the divs. This abuses the fact that the back button and refresh remember the form values.Another way is to encode the current state somewhere – in a cookie, in a URL hash… and then extract it on load and set all the values accordingly. Advantage is that it works even if you shut down the browser, and in the case of URL hashes, even if you paste the URL to your friend’s browser. (Well, maybe not for payment system 😀 but you know what I mean)