I have two <select></select> elements in my web-app one is pre-populated with country names and I want to populate the other one with states based on the country selected. I want to use jQuery and asp.net web methods (I don't have a <Form runat="server"> tag in my page) below is my webpage (html):
<form role="form" method="post" action="Login.aspx?action=register">
<div class="form-group">
<label for="exampleInputCountry">Country</label>
<select class="form-control" id="exampleInputState" name="exampleInputState">
</select>
</div>
<div class="form-group">
<label for="exampleInputCity">City/Town</label>
^__i class="fa fa-font">
<input type="text" class="form-control" id="exampleInputCity" name="exampleInputCity" />
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Sign Up</button>
</div>
</form>
<script type="text/javascript">
$("#exampleInputCountry").change(function () {
var str;
$("#exampleInputCountry option:selected").each(function () {
str += $(this).text() + " ";
});
$.ajax({
url: "/default.aspx/GetStates",
dataType: 'json',
data: { country: str },
success: function (data) {
$("#exampleInputState").fillSelect(data);
}
});
$.fn.fillSelect = function (data) {
return this.clearSelect().each(function () {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function (index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
dropdownList.add(option);
} else {
dropdownList.add(option, null);
}
});
}
});
};
$.fn.clearSelect = function () {
return this.each(function () {
if (this.tagName == 'SELECT')
this.options.length = 0;
});
};
}).change();
</script>
And this is the codebehind webmethod:
<webmethod> _
Public Function GetStates(country As String) As String
Dim ConnectionString As String
ConnectionString = ConfigurationManager.ConnectionStrings("SqlConnectionString").ToString.Trim
Dim SqlConnection As New Data.SqlClient.SqlConnection(ConnectionString)
Try
SqlConnection.Open()
Catch ex As Exception
Response.Redirect("ConnectionFailure.aspx")
End Try
Dim SqlCommand As New Data.SqlClient.SqlCommand("", SqlConnection)
SqlCommand.CommandText = "Select * From States Where Country='" & country & "'"
Dim tblStates As New XDataTable(SqlCommand)
tblStates.TableName = "States"
Return Newtonsoft.Json.JsonConvert.SerializeObject(tblStates)
End Function
It's not working, any help will be appreciated.