panels on an ASP.NET website which would display additional info if a
link or button was clicked. I found a simple tutorial and mimicked
that and it works fine, but uses the specific ID of the hyperlink to
trigger the action. My page needs a list of items, and if you click on
one, extra information appears right below the item. So what I want to
do is capture clicks on any link, read the ID, and then use the ID to
identify the ID of the related asp:Panel element.
Here's the starting point:
<script type="text/javascript">
$(function() {
$("#myButtonID").click(function(evt) {
evt.preventDefault();
$('#myPanelID').toggle('fast');
});
});
</script>
If you click on the button rendered thusly:
<input id="myButtonID" type="button" value="Hide/Show" />
The panel with id="myPanelID" is toggled (the CSS defines it so that
display is set to "none" by default.
But I want a list of these panels and buttons on my page, so I want
the code to be able to do this for any of the buttons I click.
It also works if instead of the button with the specific ID
"myButtonID" I change
$("#myButtonID").click(function(evt)
to
$("input").click(function(evt)
My impression is that this will cause the code to trigger if any input
element on the page is clicked, which is the first step to what I want
to do. My notion is that I can then get the value of the clicked
button and use that value to identify which panel to animate.
One of the FAQs on the jQuery site says I can get the value of the
button thusly:
var mybuttonval = $("input").val();
Then I could use a simple naming convention and use that value to
identify the Panel I want to animate. For example, if my button had
the value "ACME_widget-mach1" I could set the Panel I want to show
text in to "panel_ACME_Widget-mach1"
So I rewrote my code as follows:
<script type="text/javascript">
$(function() {
$("input").click(function(evt) {
var panelID = "panel_" + $("input").val();
evt.preventDefault();
$(panelID).toggle('fast');
});
});
</script>
It appeared to work just like I hoped... until I put in a second
button/panel pair, with button ID= ACME_widget-mach2 and panel ID=
panel_ACME_widget-mach1. What happens is, regardless of which button I
click, only the first panel, the one with ID=panel_ACME_widget-mach1
is toggled.
It's as if when any button is clicked, the value I am getting is the
value of the first button in the collection. I put in an alert box
right after declaring the variable to test this:
alert(panelID);
and sure enough, the value that displays is the value assigned to the
first of these buttons on the page.
So what am I doing wrong here? How can I get the value of the button
that is actually clicked?
Thanks!
Alan
No comments:
Post a Comment