Here I am going to mention the steps for how to use Ajax to
populate the data for the html Select list and how we can add the select option
to html select element.
So below are the steps
Step 1) Create the spring action which is going to serve the
Ajax request (I have used spring 3.0 controller)
@RequestMapping(value = "/countryList", method =
RequestMethod.GET)
@ResponseBody
public
HashMap<String, String> countryList(HttpServletResponse response) {
HashMap<String,
String> map = new HashMap<String, String>();
map.put("India
", "India");
map.put("AUS",
"AUS");
map.put("US",
"US");
return
map;
}
|
Step 2) Now next step is to set place holder for the list in
html form
Step 3) Now the main part, JavaScript method to call spring
action using Ajax
For JQuery we need the below JQuery library added in our JSP
or HTML
<script
type="text/javascript"
src="resources/scripts/jquery-1.9.1.js" > </script>
<script type="text/javascript"
src="resources/scripts/jquery-ui.js" > </script>
|
Here we are calling the JavaScript method on load of html
page
<body onload=" loadCountry ()">
|
Below is the JQuery method to call the spring action using JQuery
Ajax
Here we are calling /projectname/countryList URL to load the
select list data as a response which will be in the form of JSON object. Since we are using @Responsebody this will do
the JSON conversion for us.
Now here we use Jquery new Option() method to add option to select list.
var dropdown =
$('#countryId');
var defOption = new
Option("ALL","ALL");
|
Using $.each() we can
iterate the collection and add the all option to the select list.
We
can select the default option using jquery new Option(label,value, true, true).
Below
is the complete method
<<script type="text/javascript">
function loadCountry(){
$.ajax({
type: "get",
url: "/projectname/countryList ",
cache: false,
dataType: "json",
success: function(response){
var dropdown = $('#countryId');
var defOption = new Option("ALL","ALL");
$(defOption).html("ALL");
$('#countryId').append(defOption)
$.each(response, function(index) {
var selected = cument.getElementById("countryIdSelect").value;
if (selected == response[index]) {
var option = new Option(response[index],response[index], true, true);
$(option).html(response[index]);
$('#countryId').append(option)
} else {
var option = new Option(response[index],response[index]);
$(option).html(response[index]);
$('#countryId').append(option)
}
});
},
error : function(response) {
alert('Error while request..');
}
});
}
</script>
|
No comments:
Post a Comment