So I have a two radio buttons. If RadioButton1 is selected, I want Panel1 to be visible and Panel2 to be hidden. If RadioButton2 is selected, I want Panel2 to be visible and Panel1 to be hidden. Is there a way to do this without requiring a postback?
+1
A:
You can do this with a little javascript. Add an onclick handler to both radio buttons and call a function to update the view:
<input type="radio" id="radio_1" onclick="updateView">Radio 1
<input type="radio" id="radio_2" onclick="updateView">Radio 2
<script>
function updateView() {
var radio_1 = document.getElementById("radio_1");
// etc... get radio 2 and panels the same way
panel_1.style.display = radio_1.checked ? "block" : "none";
panel_2.style.display = radio_2.checked ? "block" : "none";
}
</script>
Ray
2010-01-16 20:30:26
+1
A:
There's essentially two ways to do this: completely client-side and server-side with async postback.
Client-Side:
CSS:
.hidden { display: none; }
Javascript:
toggleDiv = function(id, opt) {
_id = document.getelementbyid(id);
if (opt == "show") {
_id.style.display = "block";
} else {
_id.style.display = "hidden";
}
}
ASPX:
<asp:radiobutton id="rbOne" runat="server" />
<asp:radiobutton id="rbTwo" runat="server" />
<div id="panel1" class="hidden">
<p>Panel 1</p>
</div>
<div id="panel2" class="hidden">
<p>Panel 2</p>
</div>
Code-Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Apply onclick handlers to the radio buttons
If Not Page.IsPostBack Then
rbOne.Attributes.Add("onclick", "toggleDiv('" & rbOne.ClientId() & "', 'show'); toggleDiv('" & rbTwo.ClientId & "', 'hide');")
rbTwo.Attributes.Add("onclick", "toggleDiv('" & rbOne.ClientId() & "', 'hide'); toggleDiv('" & rbTwo.ClientId & "', 'show');")
End If
End Sub
Server-Side
ASPX:
<asp:UpdatePanel id="upRadioButtons" runat="server">
<asp:radiobutton id="rbOne" runat="server" autopostback="true" />
<asp:radiobutton id="rbTwo" runat="server" autopostback="true" />
<asp:multipage id="mvButtonPanels" runat="server">
<asp:view id="view1" runat="server">
<p>Panel 1</p>
</asp:view>
<asp:view id="view2" runat="server">
<p>Panel 2</p>
</asp:view>
</asp:multipage>
</asp:UpdatePanel>
Code-Behind:
Protected Sub rbOne_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbOne.CheckedChanged
mvButtonPanels.ActiveViewIndex = 0
End Sub
Protected Sub rbTwo_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbTwo.CheckedChanged
mvButtonPanels.ActiveViewIndex = 1
End Sub
There's many other ways to do this, such as using jQuery for the client-side and using a bit less hard-coded logic for the server side.
Paperjam
2010-01-16 20:33:21