How do I display a field when I click a link? (JavaScript)
5 answers
The main approach is to switch the CSS display using Javascript. This is a breakout from the below code:
- Attaching an event to links on page load. This is what the part does
window.onload
. - Define links and field with
document.getElementById
- Using an anonymous function to capture the display of a display
-
Switch display with
style.display
.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Onclick Example</title> <script type="text/javascript"> window.onload = function(){ var link = document.getElementById('rulink'); var box = document.getElementById('box'); var close = document.getElementById('close'); link.onclick = function(){ box.style.display = 'block' } close.onclick = function(){ box.style.display = 'none'; } } </script> <style> div{ display:none; background:#f00; width:100px; } </style> </head> <body> <a href="javascript:void(0)" id="rulink">report user</a> <div id="box"> <ul> <li>abc</li> <li>def</li> </ul> <a href="javascript:void(0)" id="close">Close</a> </div> </body>
+1
a source to share
You can do it this way, but it's pretty crude:
<a href="" onclick="document.getElementById('something').style.display='inherit';return false" >###</a>
<input style="display:none" type="text" id="something" />
For the "important" way, but understanding how it works is important.
It's worth using a JavaScript framework. JQuery is by far the most popular, and it can make your UI a lot easier.
You can shorten this onclick to:
$('#something').show()
0
a source to share
<script>
document.getElementById("showHide").onclick = function() {
var theDiv = document.getElementById("foo");
if(theDiv.style.display == 'none') {
theDiv.style.display = 'block';
this.innerHTML = 'Hide';
} else {
theDiv.style.display = 'none';
this.innerHTML = 'Show';
}
}
</script>
<span id="showHide">Show</span>
<div id="foo" style="display:none">
<form method="post">
<h3>Here are some reasons</h3>
Blah: <input type="checkbox"/><br />
Blah: <input type="checkbox"/><br />
Blah: <input type="checkbox"/><br />
<input type="submit" value="submit" />
</form>
</div>
Try it here: http://jsfiddle.net/8TNmn/2/ and see Click to show more - JS perhaps?
0
a source to share