Not sure what I am doing wrong here but the on change function is not hitting for some reason. I hope someone here can point me in the right direction.
I have a view that has some bootstrap tabs, inside one of those tabs I have a dropdown list. What I want to happen is, when the user selects a year, it make an ajax call to controller, gets the json data and populates a table with the data. Here is my code:
In the View:
<div id="StatementsTab" class="tab-pane fade">
<div class="text-left dash-left-padding dash-right-col-content-billing">
<select class="form-control edi-blue" id="ddlStatements">
<option value="0">VIEW STATEMENTS</option>
<option value="#DateTime.Now.Year">#DateTime.Now.Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-1).Year">#DateTime.Now.AddYears(-1).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-2).Year">#DateTime.Now.AddYears(-2).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-3).Year">#DateTime.Now.AddYears(-3).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-4).Year">#DateTime.Now.AddYears(-4).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-5).Year">#DateTime.Now.AddYears(-5).Year STATEMENTS</option>
</select>
<br />
<table id="statementtbl">
<tr>
<td></td>
</tr>
</table>
and the jquery:
$("#ddlStatements").change(function () {
console.log("change function yes");
var yr = $("#ddlStatements").val();
if (yr > 0){
$.ajax({
//var url = '../LabOrder/DeletePatientNoteAttachment?PatientNotes=' + JSON.stringify(yr);
url: '..Members/GetStatements',
data: 'Year=' + yr, // Send value of the drop down change of option
dataType: 'json', // Choosing a JSON datatype
success: function (data) {
console.log("success");
// Variable data contains the data you get from the action method
},
error: function (ex) {
console.log(ex);
}
});
}
});
I am not sure why but the console log is not being hit. Please help...
Suppose I am having three dropdownlist controls named dd1, dd2 and dd3. The value of each dropdownlist comes from database. dd3's value depends upon value of dd2 and dd2's value depends on value of dd1. Can anyone tell me how do I call servlet for this problem?
There are basically three ways to achieve this:
Submit form to a servlet during the onchange event of the 1st dropdown (you can use Javascript for this), let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database as a Map<String, String>, let it store them in the request scope. Finally let JSP/JSTL display the values in the 2nd dropdown. You can use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag for this. You can prepopulate the 1st list in the doGet() method of the Servlet associated with the JSP page.
<select name="dd1" onchange="submit()">
<c:forEach items="${dd1options}" var="option">
<option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
</c:forEach>
</select>
<select name="dd2" onchange="submit()">
<c:if test="${empty dd2options}">
<option>Please select parent</option>
</c:if>
<c:forEach items="${dd2options}" var="option">
<option value="${option.key}" ${param.dd2 == option.key ? 'selected' : ''}>${option.value}</option>
</c:forEach>
</select>
<select name="dd3">
<c:if test="${empty dd3options}">
<option>Please select parent</option>
</c:if>
<c:forEach items="${dd3options}" var="option">
<option value="${option.key}" ${param.dd3 == option.key ? 'selected' : ''}>${option.value}</option>
</c:forEach>
</select>
Once caveat is however that this will submit the entire form and cause a "flash of content" which may be bad for User Experience. You'll also need to retain the other fields in the same form based on the request parameters. You'll also need to determine in the servlet whether the request is to update a dropdown (child dropdown value is null) or to submit the actual form.
Print all possible values of the 2nd and 3rd dropdown out as a Javascript object and make use of a Javascript function to fill the 2nd dropdown based on the selected item of the 1st dropdown during the onchange event of the 1st dropdown. No form submit and no server cycle is needed here.
<script>
var dd2options = ${dd2optionsAsJSObject};
var dd3options = ${dd3optionsAsJSObject};
function dd1change(dd1) {
// Fill dd2 options based on selected dd1 value.
var selected = dd1.options[dd1.selectedIndex].value;
...
}
function dd2change(dd2) {
// Fill dd3 options based on selected dd2 value.
var selected = dd2.options[dd2.selectedIndex].value;
...
}
</script>
<select name="dd1" onchange="dd1change(this)">
<c:forEach items="${dd1options}" var="option">
<option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
</c:forEach>
</select>
<select name="dd2" onchange="dd2change(this)">
<option>Please select parent</option>
</select>
<select name="dd3">
<option>Please select parent</option>
</select>
One caveat is however that this may become unnecessarily lengthy and expensive when you have a lot of items. Imagine that you have 3 steps of each 100 possible items, that would mean 100 * 100 * 100 = 1,000,000 items in JS objects. The HTML page would grow over 1MB in length.
Make use of XMLHttpRequest in Javascript to fire an asynchronous request to a servlet during the onchange event of the 1st dropdown, let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database, return it back as XML or JSON string. Finally let Javascript display the values in the 2nd dropdown through the HTML DOM tree (the Ajax way, as suggested before). The best way for this would be using jQuery.
<%# page pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2263996</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#dd1').change(function() { fillOptions('dd2', this); });
$('#dd2').change(function() { fillOptions('dd3', this); });
});
function fillOptions(ddId, callingElement) {
var dd = $('#' + ddId);
$.getJSON('json/options?dd=' + ddId + '&val=' + $(callingElement).val(), function(opts) {
$('>option', dd).remove(); // Clean old options first.
if (opts) {
$.each(opts, function(key, value) {
dd.append($('<option/>').val(key).text(value));
});
} else {
dd.append($('<option/>').text("Please select parent"));
}
});
}
</script>
</head>
<body>
<form>
<select id="dd1" name="dd1">
<c:forEach items="${dd1}" var="option">
<option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
</c:forEach>
</select>
<select id="dd2" name="dd2">
<option>Please select parent</option>
</select>
<select id="dd3" name="dd3">
<option>Please select parent</option>
</select>
</form>
</body>
</html>
..where the Servlet behind /json/options can look like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String dd = request.getParameter("dd"); // ID of child DD to fill options for.
String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for.
Map<String, String> options = optionDAO.find(dd, val);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
Here, Gson is Google Gson which eases converting fullworthy Java objects to JSON and vice versa. See also How to use Servlets and Ajax?
Judging by your question, you're really not using a web framework but using servlets to render html.
I'll be nice and say that you're about a decade behind the times :), people use JSPs (and a web framework like struts) for this sort of thing. However, having said that, here goes:
Create a hidden field in your form and set the value to '1', '2' or '3' depending on which drop down is to be populated;
In your servlet, capture this value (request.getParamter()) and use it a 'case'/if/else statement to return the appropriate dropdown values.
I'll say it again, just use a web-framework, or atleast plain old jsp to do this.
You may need multiple servlets for this.
Servlet 1: Load the values for the first drop down list from the database. On the JSP page construct the drop down list. On the user selecting a value submit to servlet two.
Servlet 2: retrieve the value from the first list and perform your database search for the values of the second list. Construct the second list. When the user selects the second value submit it to servlet 3.
Servlet 3: retrieve the value selected in the second drop down and perform the database search to get values for the last drop down.
You may want to consider AJAX to make the populating of the lists appear seamless to the users. jQuery has some very nice plugins for making this quite easy if you are willing to do that.
<form action="servlet2.do">
<select name="dd1" onchange="Your JavaScript Here">
<option>....
</select>
</form>
You can write JavaScript that submits the form in the onchange event. Again, If you use an existing library like jQuery it will be 10 times simpler.
That was an awesome simple solution. I like how small the JQuery code is and really appreciate the link to the GSON API. All the examples made this an easy implementation.
Had one issue on building the JSON server URL with the reference to the parent SELECT ( e.g. $(this).val() ) [needed to specify the :selected attribute]. I've modified the script a little to include the suggested updates. Thanks for the initial code.
<script>
$(document).ready(function()
{
$('#dd1').change(function() { fillOptions('dd1', 'dd2'); });
$('#dd2').change(function() { fillOptions('dd2', 'dd3'); });
});
function fillOptions(parentId, ddId)
{
var dd = $('#' + ddId);
var jsonURL = 'json/options?dd=' + ddId + '&val=' + $('#' + parentId + ' :selected').val();
$.getJSON(jsonURL, function(opts)
{
$('>option', dd).remove(); // Clean old options first.
if (opts)
{
$.each(opts, function(key, value)
{
dd.append($('<option/>').val(key).text(value));
});
}
else
{
dd.append($('<option/>').text("Please select parent"));
}
});
}
</script>
I have two select option HTML: Category, subCategory, and subCategory must be dependence of Category ( A item as Category contains many subCategory).
My code to show Category:
<select id="categoryID">
#foreach($category as $item)
<option id="{{$item->id}}">{{$item->name}}</option>;
#endforeach
</select>
subCategory:
<select id="sub_category">
#foreach($sub_category as $item)
<option>{{$item->name}}</option>;
#endforeach
</select>
I want to when anyone selected a item in Category, it will call Web service like '/change_category', and return new variable $sub_category dependence ID of Category you selected.
Don't think about function return new variable $sub_category, I just want to ask: How to call Web service when selected option? Thanks.
<select id="categoryID" onchange="changeCategory(this)">
#foreach($category as $item)
<option id="{{$item->id}}">{{$item->name}}</option>;
#endforeach
</select>
<script type="text/javascript">
function changeCategory(id){
var category = id[id.selectedIndex].id;
$.ajax({
type: "POST",
url: url,
data: {
id: category
},
success: function (data) {
//push data here
}
});
}
</script>
I load values for select2 like the following way.
Declare the Type
var AdjustmentType = Backbone.Model.extend({
url : Hexgen.getContextPath("/referencedata/adjustmenttype")
});
create instance for the Type
var adjustmentTypes = new AdjustmentType();
load the values to select2 box
adjustmentTypes.fetch({
success : function() {
for(var count in adjustmentTypes.attributes) {
$("#adjustment-type").append("<option>" + adjustmentTypes.attributes[count] + "</option>");
}
}
});
$("#adjustment-type").select2({
placeholder: "Select Adjustment Type",
allowClear: true
});
My HTML Code
<div class="span4">
<div>ADJUSTMENT TYPE</div>
<select id="adjustment-type" tabindex="5" style="width:200px;">
<option value=""></option>
</select>
</div>
when i load this for the first it is not giving any exception but if i Refresh or navigate to different URL i get the following exception:
Uncaught query function not defined for Select2 adjustment-type
"Query" refers to the list by which to check your search terms against. You need to make sure that your data property is a proper array of objects (ie. your options elements).
I have a SELECT LIST MENU containing products and on this menu i use onChangeevent. when you select any product, it load company name of that product.Below is the function which i used,
function getcompany(element) {
var strURL="getcompany.php?product="+element.value;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
element.parentNode.parentNode.getElementsByClassName('companydiv')[0].innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
And my html code is,
<select name="product" onChange="getcompany(this)">
<option value="1" >Product1</option>
<option value="2" >Product2</option>
</select>
<div class="companydiv">Product result will be shown here</div>
The above code work but now i want to use jquery autocomplete instead of SELECT LIST MENU because my product list containing more then 1000 products.
My Autocomplete code is,but i dont know where i'm wrong
<input name="product" id="product" type="text" onkeyup="getcompany(this)" />
Some other answers i already checked but i'm not satisfied with anyone, some of them are below
jQuery AutoComplete Trigger Change Event
Jquery Autocomplete onChange event
http://forum.jquery.com/topic/autocomplete-and-change-event
I could not find your error here, however I could make what you are trying to do. I used jquery here. jsFiddle