Reputation: 1511
I'm hiding/showing a div based on a selected checkbox.
<input type="checkbox" id="other" name="os[other]" value="6" onclick="toggle_form_element('os[other]')">
Here is my Javascript Function:
function toggle_form_element(id) {
if ((document.getElementsByName(id)[0].checked)) {
document.getElementById('sometimesHidden').style.display = 'block';
} else {
document.getElementById('sometimesHidden').style.display = 'none';
}
}
At the moment this works fine. But if I'm submitting these values and saving them to a session. These Session is used to set the checkbox to checked="checked"
like this:
<input type="checkbox" id="other" name="os[other]" value="6" onclick="toggle_form_element('os[other]')" <?PHP if(!empty($_SESSION['register']['os']['other'])) echo "checked=\"checked\""; ?>>
So if I'm reloading the page, the checkbox is already checked because of the available $_SESSION
var. But the hidden div isn't visible. So how can I extend my JS Function that it is not only working "onclick". What should i use to check it always?
Upvotes: 1
Views: 1890
Reputation: 313
You have to call toggle_form_element also when page is loaded, so use and in your init function call toggle_form_element:
function init() {
toggle_form_element("other");
}
Upvotes: 1
Reputation: 78565
You need to check the status of this checkbox on page load
<body onload="toggle_form_element(id);">
Or if you're using jQuery:
$(function() {
// This code executes when the page loads
toggle_form_element(id);
});
Upvotes: 3