[英]hide/show div after page load and based on checkbox
I'm hiding/showing a div based on a selected checkbox. 我正在隐藏/显示基于所选复选框的div。
<input type="checkbox" id="other" name="os[other]" value="6" onclick="toggle_form_element('os[other]')">
Here is my Javascript Function: 这是我的Javascript函数:
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: 这些Session用于将复选框设置为
checked="checked"
如下所示:
<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. 因此,如果我正在重新加载页面,则由于可用的
$_SESSION
var,已经选中了复选框。 But the hidden div isn't visible. 但隐藏的div是不可见的。 So how can I extend my JS Function that it is not only working "onclick".
那么我怎样才能扩展我的JS函数,它不仅仅是“onclick”。 What should i use to check it always?
我应该用什么来检查呢?
You need to check the status of this checkbox on page load 您需要在页面加载时检查此复选框的状态
<body onload="toggle_form_element(id);">
Or if you're using jQuery: 或者如果你正在使用jQuery:
$(function() {
// This code executes when the page loads
toggle_form_element(id);
});
You have to call toggle_form_element also when page is loaded, so use and in your init function call toggle_form_element: 您还必须在加载页面时调用toggle_form_element,因此在init函数中使用和调用toggle_form_element:
function init() {
toggle_form_element("other");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.