How to have a control dynamically appear (after choosing a dropdown option)
So say I have a dropdown control, and after the user uses the drop down, I want a checkbox and label to appear, AJAX style, without a full pos开发者_运维技巧tback.
How can I implement something like this? Examples of code (or links to them) would be great.
I played around with this some using updatepanels but I can't get it working right...
You could achieve this with something like this:
<script type="text/javascript">
function showOptions(val) {
$('.option').hide();
$('.option' + val).show();
}
</script>
<style>
.option { border:solid 1px blue; display: none; }
</style>
<select id="dropdown" onchange="showOptions(this.value)">
<option value="1">select an option:</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<div class="option option1">put controls for option 1 here</div>
<div class="option option2">put controls for option 2 here</div>
<div class="option option3">put controls for option 3 here</div>
Note: this is using jquery.
You can see and experiment with a working example here: http://jsbin.com/owoho
I've put together a little example (using jQuery) to help you get started:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// bind an event handler to the select's change event
$("#testSelect").change(function() {
// create a label from the text of the selected option
var $label = $("<label>" + $(this).text() + "</label>");
// create a checkbox
var $checkbox = $('<input type="checkbox"/>');
// append the label and checkbox to the next div, reveal it with animation
$(this).next("div")
.empty()
.append($label)
.append($checkbox)
.show("slow");
});
});
</script>
<select id="testSelect">
<option value="foo" selected="selected">Hello</option>
<option value="test">Wooo</option>
</select>
<div style="display:none"></div>
Well, if you were just wanting to post some data to the server when the dropdownlist changes than i would just use jQuery (my preference).
<asp:DropDownList ID="DropDown" runat="server" onchange="javascript: ajaxCall();">
</asp:DropDownList>
Then your javascript could look like this.
function ajaxCall() {
$.ajax({
type: "POST",
url: "Services/Services.aspx/SomeMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}", // send some data if you need to
beforeSend: function() {
//do some things before the request is made
},
success: function(msg) {
chkBox.show();
spanOrDivName.show();
}
});
};
There are many ways to make an ajax call with jQuery, but I'm using this one because it's the most robust and I'm not sure what else you need it to do.
精彩评论